Advertisement
micha_b

readfile.c

Nov 17th, 2022
109
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.25 KB | Source Code | 0 0
  1. /*
  2.  * readfile.c
  3.  *
  4.  * Demonstration on how to get filesize of a given file,
  5.  * open it and print it to console, using C standard library
  6.  *
  7.  */
  8. #include <stdio.h>
  9. #include <stdlib.h>
  10. #include <string.h>
  11.  
  12. long int size = 0;
  13. char *content;
  14.  
  15. char* readFile(char* filename)
  16. {
  17.     FILE* file = fopen(filename,"r");
  18.     if(file == NULL)
  19.     {
  20.         return NULL;
  21.     }
  22.  
  23.     fseek(file, 0, SEEK_END);
  24.     size = ftell(file);
  25.     rewind(file);
  26.  
  27.     content = calloc(size + 1, 1);
  28.  
  29.     fread(content,1,size,file);
  30.  
  31.     return content;
  32. }
  33.  
  34. int main(int argc,char **argv)
  35. {
  36.     FILE *file;
  37.     char *myfile = calloc(256, sizeof(char));
  38.    
  39.     if(myfile)
  40.     {
  41.         /* get filesize */
  42.         file = fopen("readfile.c", "r");
  43.         fseek(file, 0, SEEK_END);
  44.         size = ftell(file);
  45.         rewind(file);
  46.         fclose(file);
  47.        
  48.         printf("File size: %ld\n", size);
  49.        
  50.         /* get some extra RAM...*/
  51.         myfile = realloc(myfile, sizeof(char) * 8);
  52.        
  53.         /* get file content */
  54.         myfile = readFile("readfile.c");
  55.        
  56.         /* output file content */
  57.         printf("%s", myfile);
  58.         printf("\nTime to leave!\n\n");
  59.        
  60.         /* Free memory and exit */
  61.         //free(content);
  62.         free(myfile);
  63.        
  64.         return EXIT_SUCCESS;
  65.     }
  66.    
  67.     /* if calloc() has failed... */
  68.     return EXIT_FAILURE;
  69. }
  70.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement