1

I am having trouble writing to ofstream pointer and this is quite perplexing as I really don't see anything that is missing anymore. Note, this is a follow up from this question: C++ vector of ofstream, how to write to one particular element

My code is as follows:

std::vector<shared_ptr<ofstream>> filelist;

void main()
{
  for(int ii=0;ii<10;ii++)
  {
     string filename = "/dev/shm/table_"+int2string(ii)+".csv";
     filelist.push_back(make_shared<ofstream>(filename.c_str()));
  }

  *filelist[5]<<"some string"<<endl;
  filelist[5]->flush();
  exit(1);

}

This does doesn't write anything to the output file but it does create 10 empty files. Does anybody know what might possibly be wrong here?

EDIT: I ran some further tests. I let the code run without exit(1) until completion, over all files until all callbacks are finished. It turns out that some files are not empty, while others that should have data are empty.

There is plenty of disk space, and I know I have more file descriptors than are necessary for this. Any explanation for why some of the files would be written properly while others are not?

4

2 回答 2

2

我会尝试:(*filelist[5])<<"some string\n";

但是,我猜想您可能打算在循环中写入文件——按原样,您只写入一个文件。

哦,在 C++ 中,你不想使用exit.

编辑:这是一个快速(经过测试)的独立演示:

#include <fstream>
#include <string>
#include <vector>

std::vector<std::ofstream *> filelist;

int main() {
  for(int ii=0;ii<3;ii++)
  {
    char *names[] = {"one", "two", "three"};
     std::string filename = "c:\\trash_";
     filename += names[ii];
     filename += ".txt";
     filelist.push_back(new std::ofstream(filename.c_str()));
  }

  for (int i=0; i<filelist.size(); i++) {
    (*filelist[i])<<"some string\n";
    filelist[i]->close();
  }
}

但是请注意,它生成的文件名是针对 Windows 的,而原始文件名(显然)是针对类似 Unix 的。对于类 Unix 操作系统,您需要/想要一个不同的文件名字符串。

于 2013-04-01T18:23:53.940 回答
0

在调用之前尝试关闭exit文件filelist[5]->close();。您已经用打开的文件中止了一个进程,这意味着您的写入可能没有进入操作系统缓冲区或在进程退出时被丢弃。您还可以删除退出调用,它可能会解决问题。IO 对中止进程的结果很难确定,因此最好尝试避免使用活动 IO 中止或假设任何活动 IO 在中止时都会失败。

于 2013-04-01T18:33:07.527 回答