Search code examples
c++file-iofopenfwritefclose

fclose, fopen and fwrite issues with writing multiple files


I have a program that records data from a serial port. Every so often, I want to split up files such that the data logs don't become very large. The problem is, after I recreate the FILE* and try to write into it, the program crashes. No compiler errors/warnings before hand also...

The program does create one log for the first time interval, but once it's time to create a new data log, it crashes at the fwrite.

First off, initializations/declarations.

char * DATA_DIR = "C:\DATA";
sprintf(path,"%s%s%s",DATA_DIR,curtime,".log"); //curtime is just the current time in a string
FILE * DATA_LOG = fopen(path, "wb+");   

And later on in a while loop

if(((CURRENT_TIME-PREVIOUS_TIME) > (SEC_IN_MINUTE * MINUTE_CHUNKS) ) && (MINUTE_CHUNKS != 0) && FIRST_TIME == 0) //all this does is just checks if its time to make a new file
{
    fclose(DATA_LOG); //end the current fileread

    char * path; 
    char curtime[16];

    //gets the current time and saves it to a file name
    sprintf(curtime , "%s" , currentDateTime());
    sprintf(path,"%s%s%s",DATA_DIR,curtime,".log");

    DATA_LOG = fopen(path, "wb+"); //open the new file

    //just some logic (not relevant to problem)
    PREVIOUS_TIME = CURRENT_TIME; 
    newDirFlag = 1;
}
fwrite(cdata , sizeof(char) , numChars , DATA_LOG); //crashes here. cdata, sizeof, and numChars don't change values

Any ideas why is this happening? I'm stumped.


Solution

  • Your MAIN problem is that char * path; has no memory assigned to it. This means that you are writing to some RANDOM [1] location in memory.

    I would suggest that you use char path[PATH_MAX]; - that way you don't have to worry about allocating and later deallocating the storage for your path.

    Alternatively, you could use:

    stringstream ss;
    
    ss << DATA_DIR << currentDateTime() << ".log";
    string path = ss.str();
    fopen(path.c_str(), "wb+")
    

    which is a more C++ style solution.

    [1] By random, I don't mean truly a random number, but some unknown value that happens to be in that location on the stack. It is almost always NOT a good place to store a string.