fstream open是否有较大文件的问题?

Sun*_*day 0 c++ unix fstream

我正在尝试/usr/share/dict/words使用以下代码打开:

fstream f;
f.open("/usr/share/dict/words");

// why is this returning false?
bool open = f.is_open();
Run Code Online (Sandbox Code Playgroud)

我想知道为什么f.is_open()返回假?

更多信息:当我尝试包含20行的小型测试文件时f.is_open()返回true.也许f.open是试图将整个文件加载到内存中?

rve*_*rve 6

它不起作用,因为您打开文件进行读写.除非您以root用户身份运行,否则您无权写入此文件.

如果你打开它只是为了阅读它将工作:

f.open("/usr/share/dict/words", fstream::in);
Run Code Online (Sandbox Code Playgroud)


nos*_*nos 5

fstream.open() 函数声明如下:

 void open (const char *filename,
        ios_base::openmode mode = ios_base::in | ios_base::out );
Run Code Online (Sandbox Code Playgroud)

即它打开文件进行读写。除非您以 root 身份运行,否则您的进程可能无权打开该文件进行写入。打开它以仅供阅读

  f.open("/usr/share/dict/words", ios_base::in);
Run Code Online (Sandbox Code Playgroud)

  • ...或者更好地将流类型更改为“ifstream”,因为只能对其进行输入 (5认同)