Advertisement
STANAANDREY

read file content

Sep 30th, 2023
1,001
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.54 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <sys/stat.h>
  4.  
  5. char *fileContents(const char path[]) {
  6.     struct stat st;
  7.     stat(path, &st);
  8.  
  9.     FILE *file = fopen(path, "r");
  10.     if (file == NULL) {
  11.         return NULL;
  12.     }
  13.  
  14.     char *s = (char*)calloc(st.st_size + 1, sizeof(char));
  15.     if (s == NULL) {
  16.         fclose(file);
  17.         return NULL;
  18.     }
  19.     fread(s, sizeof(char), st.st_size, file);
  20.     fclose(file);
  21.     return s;
  22. }
  23.  
  24. int main() {
  25.     const char *s = fileContents("data.txt");
  26.     puts(s);
  27.     return 0;
  28. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement