James Wang
James Wang

Reputation: 55

C - Using fgetc on a write file

Say we have a file pointer like this:

FILE *output = fopen("test.out", "w");

After writing to it, I want to read it using fgetc

However when I do:

char c1 = fgetc(output);

and then I print out c1 I get that c1 equals -1 which means there was an error in fgetc. Is it because I opened the file using "w"?

How can I read and write from the same file in the same function?

Upvotes: 0

Views: 354

Answers (2)

Remy Lebeau
Remy Lebeau

Reputation: 598029

You can't read from a write-only file. Open the file for read/write access using "w+" instead.

Also, after you write to the file, you have to seek backwards with fseek() before you can then read what you previously wrote.

Upvotes: 1

Jeremy Friesner
Jeremy Friesner

Reputation: 73294

If you want to be able to both read and write the file, you should open it in write/update mode (ie pass “w+” to the mode argument instead of just “w”)

Also be sure to do a frewind() or fseek() before trying to read from the file, otherwise you’ll be trying to read past the end of the file’s data.

Upvotes: 2

Related Questions