jusaca
jusaca

Reputation: 173

What is the correct way of changing mode of fopen after checking if file exists?

In my programm, I want to check if a logfile already exists and then write some data into it. Therefore I first opened it with mode "a". If this returned NULL, I reopend it with "w", wrote the header and opened it with "a" again to append the data. But after some time I always got "Too many open files" as error - so obviously opening the same file to the same pointer still opens a new handle (I wasn't aware of that). But now I'm not entirely sure how to write that part of the code - do I always have to fclose and then fopen again?

FILE *target;       
target= fopen (ComplPath, "a");

if (target == NULL) 
{   
    //fclose(target); ?!?!
    target= fopen (ComplPath, "w");
    if (target != NULL) 
    {
        fprintf(target, "Header-Text \n");  
        fprintf(target, "Data" \n);
        fclose(target);
    }
    else  
    {
        printf("Error at writeToLog: %s\n", strerror(errno));
    }  
}
else    
{
    fprintf(target, "data");
    fclose(target);
}   

See after the first if: Do I have to close the file before reopening it with "w"? It seems quite inefficient to close and reopen a file all the time. Or is there in general some better way to do this task?

Upvotes: 1

Views: 1266

Answers (1)

user10678532
user10678532

Reputation:

You should just open the file once with the "a" mode, and use ftell() to know if that created a new file.

Contrary to what your question suggests, both "a" and "w" will create a new file if it doesn't exist. The difference is that "w" will truncate it to zero length if it already exists.

FILE *target;       
target= fopen (ComplPath, "a");
if (!target) {
    /* error out */
}
if (ftell(target) == 0) {
    /* write the header */
}

Upvotes: 1

Related Questions