1

I have this code work :

#include<stdio.h>
#include<stdlib.h>
#include<string.h>

int main()
{
     FILE *File_fp = fopen("Example.dat", "w");
     char Temporary[50];
     if(!File_fp)
     {
        printf("An error occurred while creating the file.\n");
        exit(1);
     }

     fprintf(File_fp, "This is an example.\n");
     fgets(Temporary, 49, File_fp);

     printf("It was \"%s\"\n", Temporary);
     return EXIT_SUCCESS;
 }

I printed "This is an example." in the file, "Example.dat" and I want to read it again from the file by code above but there's no string in the output. Why? Please help me.

2 Answers2

3

You are opening the file in write-only mode ("w"). Use "w+" for reading and writing.

FILE *File_fp = fopen("Example.dat", "w+");
smartdroid
  • 312
  • 2
  • 10
  • Have you set the pointer to the beginning of the file before reading? – smartdroid May 27 '20 at 12:34
  • 2
    Note that if you have an update stream, you must use a positioning operation (such as `fseek()` or `rewind()`) between a write operation and a read operation, and also between a read operation that did not encounter EOF and a write operation. Plus, the program will not be able to read what it just wrote; the file position is after what was written, so a seek operation would be necessary to find what was written. – Jonathan Leffler May 27 '20 at 13:43
0

To read a file, you have to use the mode "r". Example: FILE *File_fp = fopen("Example.dat", "r");

And you made a mistake in this code. If it fails to create a file, fopen() function will return NULL. Then the value of the file pointer would be NULL. So, in your code if section will execute when the file is successfully created. So, change your code like this:

if(File_fp)
 {
  printf("An error occurred while creating the file.\n");
  exit(1);
 }

Just remove the (!) logical not sign.

Astik Roy
  • 38
  • 6
  • 1
    The second part of your answer is incorrect — `if (File_fp)` is equivalent to `if (File_fp != NULL)`. _That_ is the inverted test; the code in the question is correct, albeit inscrutable. I always write `if (File_fp == NULL)` which doesn't leave much room for misinterpretation. – Jonathan Leffler May 27 '20 at 13:41
  • Oh shit! I've made a mistake. Thanks for informing that. @JonathanLeffler – Astik Roy Jun 04 '20 at 10:41