Chris Loonam
Chris Loonam

Reputation: 5745

C char not saving to file until after app close

I'm making a c function and using it with a mac app for testing and learning purposes. When I try to print text to a file using this:

FILE *f = fopen("text.txt", "w+");
fflush(f);
if (f==NULL) {
    f = fopen("text.txt", "w+");
    saveToFile(text);
    printf("null\n");
    return 0;
}
else{
    int i = fprintf(f, "%s", text);
    if (i>0) {
        return  1;
    }
    else{
        return 0;
    }
}
fclose(f);

it prints it to the file, but only after I quit the app. Anyone know why this might be happening?

Upvotes: 1

Views: 216

Answers (1)

teppic
teppic

Reputation: 8195

You're calling return no matter what before your program can ever reach the fclose. So your program is holding off writing to the file until it's closed (because of buffering). When you terminate the program, the files are being closed for you.

Upvotes: 7

Related Questions