0

Good evening,

I know there's similar questions, which I have been sifting through, but this particular issue seems to be unique.

I am attempting to figure out how to simply read a text file into a string, and then write the string to standard output. I tried this code, but nothing is happening in the console when I call puts(). The file.txt generates properly with "hello" written, but the last if statement doesn't seem to work for some reason since it does not reach my test condition. How can I make this functional?

This was the code given by many, many examples online, only slightly modified:

#include <stdio.h>

int main()
{
    FILE *fp;
    char str[60];

    fp = fopen("file.txt","w+");
    fprintf(fp,"%s","hello");
    if(fp==NULL){
        perror("Error opening file");
        return(-1);
    }
    if (fgets (str, 60, fp)!=NULL)
        puts(str);
        printf("%s","test");
    fclose(fp);
return 0;
}

2 Answers2

0

After you have written the file, you have to fclose() the fp and re-fopen() the file for reading.

chrisaycock
  • 36,470
  • 14
  • 88
  • 125
  • 1
    Omg thank you. Been at this for a stupid amount of time >.< so silly it was that simple. I thought "w+" would allow me to read and write, but it seems I have to do exactly what you said, fclose it and fopen(file.txt, r) –  Feb 06 '17 at 04:03
0

By the time you call fgets(), the file pointer is already at end of file. Add a call to rewind(fp) before your fgets().

Oh, also when you're opening the file, put your check for fp==NULL before the call to fprintf().

ad absurdum
  • 19,498
  • 5
  • 37
  • 60
  • Aha, great solution here too. Thank you –  Feb 06 '17 at 04:06
  • This should be the accepted answer, as it is the only answer that acknowledges that OP opened the file in `"w+"` mode, and is the only answer that comments on the erroneous placement of `if(fp==NULL)...` – ad absurdum Feb 06 '17 at 09:28