gpt4 book ai didi

c++ - 为什么我不能在 Mac OS X 上读取和追加 std::fstream?

转载 作者:太空狗 更新时间:2023-10-29 23:38:08 29 4
gpt4 key购买 nike

考虑以下 C++ 程序,它获取一个文件并打印每一行。它是一个更大程序的一部分,我稍后会根据所见添加到文件中。

#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(第一行一个词,后跟一个换行符):

Rain

在我的机器 (Snow Leopard) 上,这不会打印任何内容。仔细检查后,第一次调用 getline 失败了。奇怪的是,如果我添加第二行,它也会失败:仍然没有打印任何内容!

谁能解开这个谜团?

最佳答案

当你说:

fstream file("file.txt", fstream::in | fstream::out | fstream::app);

您以附加模式打开文件 - 即在最后。只需以阅读模式打开它:

fstream file("file.txt", fstream::in );

或使用 ifstream:

ifstream file("file.txt" );

当然,正如 Earwicker 所建议的,您应该始终测试打开是否成功。

如果确定要以追加方式打开,可以显式移动读指针:

#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;
}
}
}

编辑: 似乎在打开文件时使用的标志组合会导致特定于实现的行为。上面的代码适用于 Windows 上的 g++,但不适用于 Linux 上的 g++。

关于c++ - 为什么我不能在 Mac OS X 上读取和追加 std::fstream?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2305480/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com