简体   繁体   中英

Reading from file in C using fread

I'm learning how to read content from a file in C. And I manage to scrape through the following code.

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


void read_content(FILE *file) {
  char *x = malloc(20);
  // read first 20 char
  int read = fread(x,sizeof(char),20,file);
  if (read != 20) {
     printf("Read could not happen\n");
   }
  else {
      printf("the content read is %s",x);
  }
  free(x);
  return; 
}

int main(int argc,char *argv[]) {

  FILE *fp; 
  fp = fopen("test.txt","w+");
  read_content(fp);
  fclose(fp);
  return 0;
}

But for some reason (which I'm not able to understand) I see the read bytes count as 0 .

The problem is that you open the file with the w+ mode. There are two possibilities:

  • if the file doesn't exist, it will be created empty. Reading from it immediately gives end of file resulting in fread() returning 0.
  • if the file does exist, it will be truncated ie changed into an empty file. Reading from it immediately gives end of file resulting in fread() returning 0.

If you just want to read from the file (as per your example), open it in mode r . If you want to read and write without destroying its existing content, use mode r+ .

Whatever mode you choose, always check that fopen() returns non null and print the error if it returns null (this is not the cause of your problem but is best practice).

From Man Page w+ flag:

Open for reading and writing. The file is created if it does not exist, otherwise it is truncated.

You are probably trying to open a file which doesn't exist at the path you provided, or is read-only as @WhozCraig suggested in comment. This means a new file is being created, an empty file! hence you are seeing 0 bytes read.

To sum up, The fopen is failing, in that case you need to check the return value if it is equal to -1 .
To find what was the error, you can check the errno as it is set to indicate the error.

If you are only intending to read, open the file with r flag instead of w+

The problem lies within this line of code:

fp = fopen("test.txt","w+") 

the "w+" mode, clear the previous content of the file and the file will be empty when you just going to read the file without writing anything to it. Hence, it is printing "Read could not happen" because you are trying to read an empty file.

I would suggest you to use "r+" mode, if you are willing to read and then write into the file. Otherwise, r mode is good enough for simple reading of a 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