问题描述
考虑下面的C ++程序,它接受一个文件并打印每一行。这是一个较大的程序片段,我后来根据我看到的文件附加。
Consider the following C++ program, which takes a file and prints each line. It's a slice of a larger program where I later append to the file, based on what I see.
#include <fstream>
using std::fstream;
#include <iostream>
#include <string>
using std::string;
int main()
{
fstream file("file.txt", fstream::in | fstream::out | fstream::app);
string line;
while (std::getline(file, line))
std::cerr << line << std::endl;
return 0;
}
现在应用此版本的 file.txt
(第一行一个单词,后面跟换行):
Now apply this version of file.txt
(One word on the first line, followed by a newline):
Rain
在我的机器上(Snow Leopard),这些都不打印出来。仔细检查,第一次调用getline失败。奇怪的是,如果我添加第二行,它也失败:仍然没有打印!
On my machine (Snow Leopard), this prints out nothing. On closer inspection, the first call to getline fails. Strangely, it also fails if I add a second line: still nothing is printed!
任何人都可以解决这个谜吗?
Can anyone solve this mystery?
推荐答案
当你说:
fstream file("file.txt", fstream::in | fstream::out | fstream::app);
以附加模式打开文件 - 即在结尾。只需以读取模式打开它:
you open the file in append mode - i.e. at the end. Just open it in read mode:
fstream file("file.txt", fstream::in );
或使用ifstream:
or use an ifstream:
ifstream file("file.txt" );
当然,如Earwicker所说,你应该总是测试开放成功。
And of course as Earwicker suggests, you should always test that the open succeeded.
如果您确定以追加模式打开,您可以显式移动读取指针:
If you are determined to open in append mode, you can move the read pointer explicitly:
#include <fstream>
#include <iostream>
#include <string>
using namespace std;
int main() {
fstream file( "afile.txt", ios::in | ios::out | ios::app );
if ( ! file.is_open() ) {
cerr << "open failed" << endl;
return 1;
}
else {
file.seekg( 0, ios::beg ); // move read pointer
string line;
while( getline( file, line ) ) {
cout << line << endl;
}
}
}
/ strong>似乎在文件打开中使用的标志的组合导致实现特定的行为。上面的代码在Windows上使用g ++,但在Linux上不适用于g ++。
It seems that the combination of flags used in the opening of the file leads to implementation specific behaviour. The above code works with g++ on Windows, but not with g++ on Linux.
这篇关于为什么我不能在Mac OS X上阅读和追加std :: fstream?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!