2016-05-14 137 views
-2

即使在文件末尾有空行,是否可以在文件末尾添加一行?下面是一个例子代码:忽略文件末尾的空格

void add(fstream &inputfile, int x, int y) 
    { 
     inputfile.clear(); 
     inputfile.seekg(0, ios::end); 
     while(??)        //while last line is blank space 
      inputfile.seekg(-1, ios::end); //go back one line 
     inputfile << x << "\t" << y << endl; //when while's finished add the new one 
     inputfile.seekp(0); 
    } 

为了实现这样的输出:

Input file: 
1 2 
2 3 

Wrong output file: 
1 2 
2 3 


3 4 

Correct output file: 
1 2 
2 3 
3 4 

是否有可能做这样?应该在while循环中放入什么?即使没有空格,代码也应该工作,所以我们不得不使用while语句而不是简单的语句。如果不能这样做,你有任何其他建议吗?

回答

1

转到文件结尾之前。然后使用一个循环,在下一个字符偷看(读取它没有前进)。如果它是换行符,则返回一个字符并重复循环。当你到达最后一个非换行符时,向前查找2个字节,跳过该字符和换行符。

inputfile.seekg(-1, ios::end); 
while(inputfile.peek() == '\n') { 
    inputfile.seekg(-1, ios::cur); 
} 
inputfile.seekg(2, ios::cur);