繁体   English   中英

打开一个fstream进行读写(二进制)

[英]Opening an fstream for reading/ writing (binary)

该程序中的用户可以使用许多选项:选项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;
}

声明后:

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

是否有必要显式调用open;

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

文件流可以在其构造函数中open()也可以通过调用成员函数open() 如果在调用open()之前已经打开了文件,则这是由流的错误报告的错误。 这是没有必要调用open()文件是否已经被打开。

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

std::fstream fs;

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

必须指定二进制模式吗?

是的,二进制模式永远不是默认的打开模式。 如果您需要文件处于二进制模式,则需要指定此选项。

在连续写入之前是否需要清除流?

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

在这里fs.close()不调用fs.open()是不正确的fs.close()

除非您要在流中打开新文件,否则通常无需显式调用close() 由于std::fstreamRAII类,因此close()将在其作用域的结尾(在main的结尾close()被调用。

如果需要打开新文件,则应先调用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));
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM