Ofstream 不写入文件 C++

Itz*_*984 2 c++ io file ofstream

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

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




}
Run Code Online (Sandbox Code Playgroud)

缓冲区内容为:

任务->缓冲区:elishaefla

任务->长度:10

我使用以下命令在另一个 init 函数中打开流:

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

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

知道为什么吗?

Att*_*ila 5

您没有提供足够的信息来确定地回答问题,但以下是您可能面临的一些问题:

  1. 您没有刷新缓冲区ofstream

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