Simple Reading A File Into a Buffer Using Fstat Example

Here is a simple example of reading an entire file into a buffer and using fstat

  1. /*
  2.  * file-read.c
  3.  *
  4.  * Simple program to read in an entire file into buffer
  5.  * using malloc after determining filesize using fstat.
  6.  *
  7.  * gcc -Wall file-read.c -o file-reader
  8.  *
  9.  */
  10.  
  11. #include <stdio.h>
  12. #include <stdlib.h>
  13. #include <string.h>
  14. #include <sys/stat.h>
  15. #include <inttypes.h>
  16.  
  17. #define FILENAME "mylargefile.txt"
  18.  
  19. int main(int argc, char **argv)
  20. {
  21.         struct stat file_status;
  22.        
  23.         if(stat(FILENAME, &file_status) != 0){
  24.                 perror("ERROR: Could not stat or file does not exist");
  25.         }
  26.         printf("Filesize: %s\n\n",FILENAME);
  27.         printf("b  %9jd \n", ((intmax_t)file_status.st_size));
  28.         printf("Kb %9jd \n", ((intmax_t)file_status.st_size) / 1024);
  29.         printf("Mb %9jd \n", (((intmax_t)file_status.st_size) / 1024) / 1024);
  30.         printf("Gb %9jd \n", ((((intmax_t)file_status.st_size) / 1024)/ 1024)/ 1024);
  31.        
  32.         FILE *fp = fopen (FILENAME, "r");
  33.        
  34.         char *buffer = NULL;
  35.         buffer = (char *) malloc(file_status.st_size+1); // + null terminator
  36.        
  37.         if (!fread(buffer, file_status.st_size,1,fp)) {
  38.         perror("ERROR: Could not read file");
  39.     }
  40.     buffer[file_status.st_size+1] = '\0';
  41.        
  42.         printf("%s\n",buffer);
  43.                
  44.         fclose(fp);
  45.         free(buffer);
  46.                
  47.         return 0;
  48. }
AttachmentSize
file-read.tar.gz1.4 MB

Add new comment

Filtered HTML

  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <blockquote> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.