我想读取文本文件(我是在UNIX上,可以使用升压)的最后一行。所有的方法,我知道需要通过整个文件扫描得到的最后一行是没有效率的。有没有一种有效的方式来获得唯一的最后一行?
另外,我需要这是足够强大,它的作品,即使有问题的文本文件不断被另一个进程附加。
使用seekg跳转至文件末尾,然后读回,直到找到第一个换行符。下面是一些示例代码,把我的头使用MSVC顶部。
#include <iostream>
#include <fstream>
#include <sstream>
using namespace std;
int main()
{
string filename = "test.txt";
ifstream fin;
fin.open(filename);
if(fin.is_open()) {
fin.seekg(-1,ios_base::end); // go to one spot before the EOF
bool keepLooping = true;
while(keepLooping) {
char ch;
fin.get(ch); // Get current byte's data
if((int)fin.tellg() <= 1) { // If the data was at or before the 0th byte
fin.seekg(0); // The first line is the last line
keepLooping = false; // So stop there
}
else if(ch == '\n') { // If the data was a newline
keepLooping = false; // Stop at the current position.
}
else { // If the data was neither a newline nor at the 0 byte
fin.seekg(-2,ios_base::cur); // Move to the front of that data, then to the front of the data before it
}
}
string lastLine;
getline(fin,lastLine); // Read the current line
cout << "Result: " << lastLine << '\n'; // Display it
fin.close();
}
return 0;
}
以下是测试文件。它成功了空,一个线,并在文本文件中多行数据。
This is the first line.
Some stuff.
Some stuff.
Some stuff.
This is the last line.
跳转到随后结束,并开始阅读块向后直到你找到任何你标准的线路。如果最后一块没有“结束”有一条线,你可能需要尝试和向前扫描以及(假设在一个很长的线,积极追加到文件)。
最初,这是设计来读取的最后一个系统日志条目。鉴于EOF前的最后一个字符是'\n'
我们争取回来找'\n'
的下一次出现,然后我们行存储到一个字符串。
#include <fstream>
#include <iostream>
int main()
{
const std::string filename = "test.txt";
std::ifstream fs;
fs.open(filename.c_str(), std::fstream::in);
if(fs.is_open())
{
//Got to the last character before EOF
fs.seekg(-1, std::ios_base::end);
if(fs.peek() == '\n')
{
//Start searching for \n occurrences
fs.seekg(-1, std::ios_base::cur);
int i = fs.tellg();
for(i;i > 0; i--)
{
if(fs.peek() == '\n')
{
//Found
fs.get();
break;
}
//Move one character back
fs.seekg(i, std::ios_base::beg);
}
}
std::string lastline;
getline(fs, lastline);
std::cout << lastline << std::endl;
}
else
{
std::cout << "Could not find end line character" << std::endl;
}
return 0;
}
虽然通过derpface的答案肯定是正确的,它经常会返回意外的结果。这样做的原因是,至少我的操作系统(Mac OSX版10.9.5)上,很多文本编辑器终止与“高端路线”字符他们的文件。
例如,当我打开vim,输入只是单个字符“A”(没有返回),并保存,文件现在将包含(十六进制):
61 0A
其中61是字母“a”和0A是行字符的端部。
这意味着,通过derpface代码将返回由这样的文本编辑器创建的所有文件空字符串。
虽然我当然可以想像其中一个文件终止与“高端路线”的情况下应该返回空字符串,我觉得忽略了最后的“高端路线”字与普通的文本文件打交道时会比较合适;如果该文件是由“高端路线”字符终止,我们适当地忽略它,如果文件不被“端线”字符结束,我们并不需要检查它。
我无视输入文件的最后一个字符的代码是:
#include <iostream>
#include <string>
#include <fstream>
#include <iomanip>
int main() {
std::string result = "";
std::ifstream fin("test.txt");
if(fin.is_open()) {
fin.seekg(0,std::ios_base::end); //Start at end of file
char ch = ' '; //Init ch not equal to '\n'
while(ch != '\n'){
fin.seekg(-2,std::ios_base::cur); //Two steps back, this means we
//will NOT check the last character
if((int)fin.tellg() <= 0){ //If passed the start of the file,
fin.seekg(0); //this is the start of the line
break;
}
fin.get(ch); //Check the next character
}
std::getline(fin,result);
fin.close();
std::cout << "final line length: " << result.size() <<std::endl;
std::cout << "final line character codes: ";
for(size_t i =0; i<result.size(); i++){
std::cout << std::hex << (int)result[i] << " ";
}
std::cout << std::endl;
std::cout << "final line: " << result <<std::endl;
}
return 0;
}
这将输出:
final line length: 1
final line character codes: 61
final line: a
在单一的“A”文件。
编辑:行if((int)fin.tellg() <= 0){
实际上导致问题,如果文件过大(> 2GB),因为所以tellg不只是从文件(tellg() function give wrong size of file?)开始返回的字符数。这可能是更好的单独测试文件fin.tellg()==tellgValueForStartOfFile
的开始和错误fin.tellg()==-1
。该tellgValueForStartOfFile
可能是0,但要确保一个更好的方式很可能是:
fin.seekg (0, is.beg);
tellgValueForStartOfFile = fin.tellg();
您可以使用seekg()跳转到文件的末尾,落后的阅读,伪代码如下:
ifstream fs
fs.seekg(ios_base::end)
bytecount = fs.tellg()
index = 1
while true
fs.seekg(bytecount - step * index, ios_base::beg)
fs.read(buf, step)
if endlinecharacter in buf
get endlinecharacter's index, said ei
fs.seekg(bytecount - step*index + ei)
fs.read(lastline, step*index - ei)
break
++index
我也挣扎了问题,因为我跑uberwulu的代码,同时也得到了空行。这是我发现的。我使用下列.csv文件为例:
date test1 test2
20140908 1 2
20140908 11 22
20140908 111 235
要了解在代码中的命令,请注意下面的位置及其对应的字符。 (LOC炭):......(63, '3'),(64, '5'),(65, - ),(66, '\ n'),(EOF, - )。
#include<iostream>
#include<string>
#include<fstream>
using namespace std;
int main()
{
std::string line;
std::ifstream infile;
std::string filename = "C:/projects/MyC++Practice/Test/testInput.csv";
infile.open(filename);
if(infile.is_open())
{
char ch;
infile.seekg(-1, std::ios::end); // move to location 65
infile.get(ch); // get next char at loc 66
if (ch == '\n')
{
infile.seekg(-2, std::ios::cur); // move to loc 64 for get() to read loc 65
infile.seekg(-1, std::ios::cur); // move to loc 63 to avoid reading loc 65
infile.get(ch); // get the char at loc 64 ('5')
while(ch != '\n') // read each char backward till the next '\n'
{
infile.seekg(-2, std::ios::cur);
infile.get(ch);
}
string lastLine;
std::getline(infile,lastLine);
cout << "The last line : " << lastLine << '\n';
}
else
throw std::exception("check .csv file format");
}
std::cin.get();
return 0;
}
我把亚历山德罗的解决方案和焕然一新它一点
bool moveToStartOfLine(std::ifstream& fs)
{
fs.seekg(-1, std::ios_base::cur);
for(long i = fs.tellg(); i > 0; i--)
{
if(fs.peek() == '\n')
{
fs.get();
return true;
}
fs.seekg(i, std::ios_base::beg);
}
return false;
}
std::string getLastLineInFile(std::ifstream& fs)
{
// Go to the last character before EOF
fs.seekg(-1, std::ios_base::end);
if (!moveToStartOfLine(fs))
return "";
std::string lastline = "";
getline(fs, lastline);
return lastline;
}
int main()
{
const std::string filename = "test.txt";
std::ifstream fs;
fs.open(filename.c_str(), std::fstream::in);
if(!fs.is_open())
{
std::cout << "Could not open file" << std::endl;
return -1;
}
std::cout << getLastLineInFile(fs) << std::endl;
return 0;
}