Ofstream not writing to file C++

10,764

You did not provide enough information to answer the question with certainty, but here are some of the issues you might be facing:

  1. You did not flush the buffer of the ofstream

  2. You did not close the file that you are trying to open later on (if I'm correct, outputFile is a global variable, so it is not closed automatically until the end of the program)

Share:
10,764
Itzik984
Author by

Itzik984

Updated on June 04, 2022

Comments

  • Itzik984
    Itzik984 almost 2 years

    I have this method which supposed to get a buffer and write some content to a file:

    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
    
    
    
    
    }
    

    the buffer content is:

    task->buffer: elishaefla

    task->length: 10

    i opened the stream in another init function using:

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

    but at the end, the file content is empty, nothing is being written.

    any idea why?