c++fflush

fflush() is not workign as expected


I am currently working on a project that I need file io. In this project I am often reading and writing to a file. But the thing is that I am failing to read anything in from the file. I have tried using fflush() but that does not seem to be working. I have some example code that demonstrates the same behavior below.

#include <iostream>
#include <stdio.h>
using namespace std;

int main() {
    FILE* fp = fopen("file.txt", "w+");
    fprintf(fp, "Test text");
    fflush(fp);

    char c = fgetc(fp);
    fclose(fp);
    cout << c << endl;
    return 0;
 }

Instead of c being 'T' as expected I am getting an unknown character.

I am using C style io because I want to avoid the size overhead of fstreams.


Solution

  • Looks like the pointer to file points to the end of the file, so the return is -1, hence the weird char you get. After fflush(); (witch I believe is not needed, at least for the example you produce) you can make the pointer point to the beggining of the file with 0 offset:

    //...
    fflush(fp);
    fseek(fp, 0, SEEK_SET);
    char c = getc(fp);
    //...
    

    This will return 84 witch is the correct ASCII code for the character T