0

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.

Joe
  • 13
  • 2
  • 1
    Also, Microsoft has a [fair bit to say](https://learn.microsoft.com/en-us/cpp/c-runtime-library/reference/fopen-wfopen?view=vs-2019) about switching between reading & writing in the section about the `mode` parameter. – Weather Vane Jan 11 '20 at 16:56
  • 2
    `fgetc()` returns an `int`, not a `char`. – Andrew Henle Jan 11 '20 at 17:38

1 Answers1

1

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

anastaciu
  • 23,467
  • 7
  • 28
  • 53