visoft

Pregatire 19 nov Citire siruri din fisier

Nov 19th, 2020
396
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4.  
  5. #define MAX_LINE_LEN 10000
  6. #define MAX_NO_LINES 100
  7.  
  8. /*
  9.  * On success, the function returns str.
  10. If the end-of-file is encountered while attempting to read a character, the eof indicator is set (feof).
  11.  If this happens before any characters could be read, the pointer returned is a null pointer (and the contents of str remain unchanged).
  12. If a read error occurs, the error indicator (ferror) is set and a null pointer is also returned (but the contents pointed by str may have changed).
  13.  *
  14.  */
  15.  
  16. /*
  17.  * void* malloc (size_t size);
  18.  *
  19.  *
  20.  */
  21.  
  22. int main() {
  23.     FILE * f = fopen("../in.txt", "r");
  24.  
  25.     char **tab = (char **)malloc(sizeof(char*)*MAX_NO_LINES);
  26.  
  27.     if (f == NULL)
  28.         return 100;
  29.  
  30.     char* linie = (char *)malloc(sizeof(char)* MAX_LINE_LEN);
  31.     char* ok=linie;
  32.     int n = 0;
  33.     while (ok == linie){
  34.         ok = fgets(linie, MAX_LINE_LEN, f);
  35.         tab[n] = (char*)malloc(sizeof(char) * (strlen(linie) + 1));
  36.         strcpy(tab[n], linie);
  37.         n++;
  38.     }
  39.     free(linie);
  40.  
  41.     for(int i=0;i<n;i++){
  42.         printf("%s", tab[i]);
  43.     }
  44.  
  45.     fclose(f);
  46.     return 0;
  47. }
  48.  
  49.  
RAW Paste Data