visoft

Pregatire 19 Nov scriere text in fisier

Nov 19th, 2020
403
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.     if (f == NULL)
  25.         return 100;
  26.  
  27.     char **tab = (char **)malloc(sizeof(char*)*MAX_NO_LINES);
  28.     char* linie = (char *)malloc(sizeof(char)* MAX_LINE_LEN);
  29.     char* ok=linie;
  30.     int n = 0;
  31.     while (ok == linie){
  32.         ok = fgets(linie, MAX_LINE_LEN, f);
  33.         if(ok != linie)
  34.             break;
  35.         tab[n] = (char*)malloc(sizeof(char) * (strlen(linie) + 1));
  36.         strcpy(tab[n], linie);
  37.         n++;
  38.     }
  39.     free(linie);
  40.     fclose(f);
  41.     //**************************************************  AICI AM CONTINUTUL IN MEMORIE ************//
  42.  
  43.     FILE * fout = fopen("../out.txt", "wb");
  44.     if (fout == NULL)
  45.         return 110;
  46.  
  47.     for(int i=0;i<n;i++){
  48.         //Sa numaram spatiile
  49.         int nr_spatii = 0;
  50.         for(int j = 0; j < strlen(tab[i]);j++){
  51.             int is_whitespace = tab[i][j] == ' ' || tab[i][j] == '\n' || tab[i][j] == '\r';
  52.             if(!is_whitespace)
  53.                 nr_spatii++;
  54.         }
  55.         fprintf(fout,"Number of non-spaces: %-6d : %s", nr_spatii, tab[i]);
  56.     }
  57.     fclose(fout);
  58.  
  59.     for(int i=0;i<n;i++){
  60.         free(tab[i]);
  61.     }
  62.     free(tab);
  63.  
  64.     return 0;
  65. }
  66.  
  67.  
RAW Paste Data