【问题标题】:Ofstream not writing to file C++Ofstream 不写入文件 C++
【发布时间】:2012-05-14 15:14:06
【问题描述】:

我有这个方法应该获取缓冲区并将一些内容写入文件:

void writeTasksToDevice()
{

TaskInfo *task;
unsigned int i = lastTaskWritten;

printf("writing elihsa\n");
outputFile.write(" Elisha2", 7);
//pthread_mutex_lock(&fileMutex);

for(; i < (*writingTasks).size(); i++)
{
    task = (*writingTasks).at(i);
    if(NULL == task)
    {
        printf("ERROR!!! in writeTasksToDevice - there's a null task in taskQueue. By "
                " design that should NEVER happen\n");
        exit(-1);

    }
    if(true == task->wasItWritten)
    {
        //continue;
    }
    else // we've found a task to write!
    {

        printf("trying to write buffer to file\n");
        printf("buffer = %s, length = %d\n", task->buffer, task->length);<====PRINT HERE IS OK< PRINTING WHAT IS WANTED
        outputFile.write(task->buffer, task->length); <===SHOULD WRITE HERE
        printf("done writing file\n");
    }

}

//pthread_mutex_unlock(&fileMutex);


// TODO: check if we should go to sleep and wait for new tasks
// and then go to sleep




}

缓冲区内容为:

任务->缓冲区:elishaefla

任务->长度:10

我在另一个初始化函数中打开了流:

outputFile.open(fileName, ios :: app);
if(NULL == outputFile)
{
    //print error;
    return -1;
}

但最后,文件内容为空,没有写入任何内容。

知道为什么吗?

【问题讨论】:

  • 你在什么时候检查的?请注意,它很可能正在缓冲,因此在检查之前您需要刷新或关闭流
  • 更改参数为 ios::out | ios::app
  • @luskan:如果确实是 ofstream 则没关系: ios::out 保证会被 ORed 到标志中。
  • @luskan 仍然没有写任何东西...
  • 删除了 c 标签,因为这纯粹是 c++ 问题

标签: c++ file io ofstream


【解决方案1】:

您没有提供足够的信息来肯定地回答这个问题,但以下是您可能会遇到的一些问题:

  1. 您没有刷新ofstream的缓冲区

  2. 您没有关闭稍后尝试打开的文件(如果我没记错的话,outputFile 是一个全局变量,所以直到程序结束它才会自动关闭)

【讨论】:

  • 请注意,第 6 行的字符串:"Elisha2" 正在写入,为什么会这样?
  • 我的猜测是,由于您进行了更多的写入,因此缓冲区会填满并且之前的内容会自动刷新。
  • 阿提拉,你是对的。那么我应该什么时候刷新缓冲区?程序何时结束或每次写入文件后?
  • 您可以在每次写入之后执行flush(),或者在任何方便的序列点(例如,如果由于过于频繁的刷新而导致性能问题,则在对write() 的几次后续调用结束时
  • 在我的情况下,我已经在/tmp/text.txt 中有一个文件——我用std::_S_trunc 打开它,做了一个flush() 和一个close(),但什么也没做。但是文件是打开的。我不得不删除它并让我的 C++ 程序创建它,然后它更新得很好。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-03-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多