Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

w+ not working when trying to read file content

Tags:

c

fgets

fputs

Code:

#include <stdio.h>

void main() {
    FILE *ptr;
    char buff[255];
    ptr = fopen("Test.txt", "w+");

    if (ptr != NULL) {
        printf("Success\n");
    }

    fputs("Hello", ptr);

    fgets(buff, 255, (FILE *)ptr);
    printf("%s", buff);
    fclose(ptr);
}

The file "Text.txt" has the content "Hello" when I opened it, but I just can't print it out with fgets. What did I do wrong here?

like image 548
Richard Avatar asked Jan 20 '26 14:01

Richard


1 Answers

You didn't rewind the file before reading. fseek(ptr, 0, SEEK_SET); or rewind(ptr);

like image 152
LoztInSpace Avatar answered Jan 23 '26 03:01

LoztInSpace



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!