C++流创建和写入文件问题

C++ ofstream create and write file issue

本文关键字:文件 问题 创建 C++      更新时间:2023-10-16

我的虚拟文件系统提取器有问题。

ofstream ofs(path, ios::out|ios::binary);
ofs.write(file, length);
ofs.close();

路径是例如"data/char/actormotion.txt",应该在目录data/char/文件中创建名为actormotion的文件.txt但什么也没做。

首先检查它是否打开

      std::ofstream ofs(path, ios::out|ios::binary);
      if (ofs.is_open())
      {
// write stuff
        ofs.close();
      }
      else
      {
        std::cout << "Error opening file";
      }

更有可能的是文件未打开。您可以使用bool is_open()方法进行检查。

打开流后,建议检查其状态以确保一切顺利:

ofstream ofs(path, ios::out|ios::binary);
if ( (ofs.rdstate() & std::ofstream::failbit ) != 0 ){
    //stream opened successfully, do the stuff...

在Windows系统中,您可以立即调用GetLastError()来查询错误代码。