Dan Streeter
Dan Streeter

Reputation: 1

How to read from a file using fgets?

I'm trying to read the contents of "Danfilez.txt" using fgets. However on completion the program returns a random value and i'm unsure why. I'm new to programming so any help would be greatly appreciated!

int main()
{
    FILE* Danfile = fopen ("Danfilez.txt", "w");
    char fileinfo [50];// Character arrays for file data //

    if (Danfile == NULL)
    {
        printf ("ERROR\n");

    }

    else
    {
        printf("Everything works!\n");
        fprintf (Danfile, "Welcome to Dan's file."); 
        fgets(fileinfo,50,Danfile);
        printf("%s\n",fileinfo);
        fclose (Danfile); // CLOSES FILE //
    }


    return 0;
}

Upvotes: 0

Views: 638

Answers (2)

Radoslav T.
Radoslav T.

Reputation: 1

While using fopen() you pass the option for opening as an argument to the funtion. Here is the list:

"r"  - Opens the file for reading. The file must exist. 
"w"  - Creates an empty file for writing. If a file with the same name already exists,
      its content is erased and the file is considered as a new empty file.
"a"  - Appends to a file. Writing operations, append data at the end of the 
      file. The file is created if it does not exist.
"r+" - Opens a file to update both reading and writing. The file must exist.
"w+" - Creates an empty file for both reading and writing.
"a+" - Opens a file for reading and appending.

Try using "r+" or "w+". After writing some text, your position in the file will move forward along with the text. Use rewind(FILE* filename) to move your position straight to the start of the file. For more information related to file handling i recommend checking what is inside stdio library: https://www.tutorialspoint.com/c_standard_library/stdio_h.htm

Upvotes: 0

Chris Turner
Chris Turner

Reputation: 8142

Since you're both reading and writing from the file you want to use "w+" to open the file rather than just "w".

But that won't fix things because once you've written out that text, your position in the file is still at the end, so you'll also need to reset the position before you can read anything in using fseek()

fseek(Danfile,0,SEEK_SET);

Upvotes: 2

Related Questions