简体   繁体   中英

Can I write to a new file, then read from that file within the same C program?

FILE *new = fopen("new.out", "w+"); // creates a new file that didnt exist before
char finput[50];

fprintf(new, "hello\nworld\n");

while(fgets(finput, 51, new) != NULL)
{ /*never reaches this point*/ }

What am I doing wrong? If I write to a file that doesn't already exist, is it possible to read from that file later on?

You should rewind or fseek before reading again. And please, don't call a variable new (because that is a C++ keyword).

You need to do something to change the mode between write and read. fseek is a possibility.

On streams open for update (read+write), a call to fseek allows to switch between reading and writing.

fsetpos and rewind work as well.

You've opened the file in w+ mode, which is read/write in append mode. After your fprintf() command, the file pointer is at the END of the file, meaning there's nothing to read but EOF. You have to fseek() to another point in the file, or rewind() to the beginning.

Take a look here . They advice you to check errno on error. You can use

perror("Fgets failed");

to print full error message.

To the problem: you need to call fseek when changing from write to read (always).

fseek(new, 0, SEEK_SET);

rewinds the file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM