c++ - 打开一个 fstream 进行读/写(二进制)

标签 c++ if-statement fstream ofstream

在此程序中,用户可以使用许多选项: 选项 1:记录条目(由 EOF 键终止)。 选项 2:显示记录。选项 3:退出程序。

然后用户可以重复这个过程。我希望通过查找文件末尾来避免覆盖记录,并确保 close() 和 open() 调用正确。

声明后:

fstream fs("file", ios_base::in | ios_base::out | ios_base::binary);

是否需要显式调用open;

fs.open("file", ios_base::in | ios_base::binary);

如果有必要:必须指定二进制模式吗?是否需要在连续写入之前清空流?

struct record
{
    char firstname[MAX], lastname[MAX];
    int score;
};

int main(){

  record r;
  // must the modes be listed in a particular order?
  fstream fs("file", ios_base::in |ios_base::out | ios_base::binary);

  if(choice == 1) // option 1 for writing 
  {
    fs.clear(); // is it necessary to clear?
    // is it necessary to explicitly call open [and close] within 'if'
    fs.open("file", ios_base::in | ios_base::binary); 
    fs.seekp(0, ios_base::end); //attempt to avoid overwriting previous records 

    fs.write( (char *)&r, sizeof(r) );
    fs.close(); // is it best to close the file here...
  } 
  else if(choice == 2){ /*Display records*/ }
  else if(choice == 3){ exit(1); }

  /* would it be incorrect to fs.close() here and not call fs.open() */

  return 0;
}

最佳答案

After declaring:

fstream fs("file", ios_base::in | ios_base::out | ios_base::binary);

is it necessary to explicitly call open;

fs.open("file", ios_base::in | ios_base::binary);

文件流可以在它们的构造函数中或通过调用成员函数open() 打开。如果文件在调用 open() 之前已经打开,那么这是流错误报告的错误。如果文件已经打开,则不需要调用open()

请注意,您可以默认构造文件流,因此您不必决定如何在构造时打开流。

std::fstream fs;

这是一个没有关联文件的流,所以现在您可以用正确的语义调用 open()

must binary mode be specified?

是的,二进制模式从来都不是默认的打开模式。如果您需要一个文件为二进制模式,则需要指定此选项。

is it necessary to clear the stream prior to writing successively?

成员函数clear() 用于清除错误掩码,由于读/写等失败,可以写入错误掩码。仅当存在您希望清除的错误时才可以这样做。但您可能不需要执行此操作,因为您只是在没有任何先前 IO 操作的情况下打开了文件。

would it be incorrect to fs.close() here and not call fs.open()

您通常不需要显式调用 close() 除非您想在流中打开一个新文件。因为 std::fstream 是一个 RAII类,close() 将在其作用域结束时(在 main 结束时)被调用。

如果您需要打开一个新文件,那么您应该先调用close(),然后再调用open()


另外,一个建议:如果你想在最后打开一个文件,那么使用std::ios_base::ate openmode:

if (choice == 1) {
    fs.open("file", ios_base::in | ios_base::binary | ios_base::ate);
    //                                                ^^^^^^^^^^^^^
    fs.write( (char *)&r, sizeof(r));
}

关于c++ - 打开一个 fstream 进行读/写(二进制),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30699458/

相关文章:

c++静态成员,我如何测试它

python - 尝试将邮政编码转换为二进制时找不到错误

javascript - 为什么在第一个 if 语句为 true 后,我的第二个 if 语句连续运行两次?

c++ - 使用 ifstream 在两个线程中处理同一个文件

c++ - 最小/最大逻辑和文件读取错误

c++ - 用于 GUI 的 Qt Designer C++ 或 QML

c++ - 输入结束时应为 '}'

c++ - 如何从值元组创建左值引用元组

Java Swing ;两个类,if 语句和新的 actionlisteners 放在哪里?

c++ - 打印到文件和控制台 C++