nezvers

C load text from file

May 5th, 2021 (edited)
867
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.75 KB | None | 0 0
  1. #ifndef LOAD_TEXT_H
  2. #define LOAD_TEXT_H
  3.  
  4. #include "stdio.h"
  5. #include "stdlib.h"
  6.  
  7. char* TextFromFile(const char* fileName, size_t *sizeOut){
  8.     FILE *file;
  9.  
  10.     /* Open the file */
  11.     file = fopen(fileName, "r");
  12.     if (file == NULL) {
  13.         printf("Cannot open file %s\n", fileName);
  14.         return NULL;
  15.     }
  16.  
  17.     /* Get size of file for memory allocation */
  18.     fseek(file, 0, SEEK_END);
  19.     size_t size = ftell(file);
  20.     fseek(file, 0, SEEK_SET);
  21.  
  22.     /* Allocate memory to the array */
  23.     char *textArray = (char*)malloc( (size+1) );
  24.  
  25.     /* Store the information into the array */
  26.     size_t read_count = fread(textArray, 1, size, file);
  27.     fclose(file);
  28.     textArray[read_count] = '\0';
  29.    
  30.     if (sizeOut != NULL){*sizeOut = size;}
  31.     return textArray;
  32. }
  33.  
  34. #endif //LOAD_TEXT_H
  35.  
Add Comment
Please, Sign In to add comment