Advertisement
J3st3rs_j0k3

lw7_1 for MKT 1

Mar 15th, 2024
444
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.86 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #include <locale.h>
  5. #define n 80
  6.  
  7. int main()
  8. {
  9.     setlocale(LC_ALL,"Rus");
  10.     FILE *f1,*f2;
  11.     int count;
  12.     char s[n],sx[n],*p,scount[n];
  13.     if (!(f1=fopen("text.txt","r")))  //проверяем открылся ли файл
  14.     {
  15.         printf("Не удалось открыть файл\n");
  16.         return 1;
  17.     }
  18.     if (!(f2=fopen("temp.txt","w")))  //проверяем создался ли временный файл
  19.     {
  20.         printf("Не удалось создать файл\n");
  21.         fclose(f1);
  22.         return 2;
  23.     }
  24.     while((p=fgets(s,n,f1))!= NULL)  //построчно читаем данные из файла
  25.     {
  26.         count=0;
  27.         strcpy(sx,s);  //создаём копию строки, т.к. команда strtok добавляет \0 в строку, с которой взаимодействует. затем будем в файл будем записывать уже копию
  28.         p=strtok(s," ");
  29.         while(p!=NULL)  //считаем кол-во слов в строке
  30.         {
  31.             count++;
  32.             p=strtok(NULL," ");
  33.         }
  34.         sprintf(scount,"(%d) ",count);  //переводим число в строку
  35.         p=strchr(sx,'\n');  //убираем \n, который приписался к sx в strcpy(sx,s)
  36.         if (p)
  37.             *p=' ';
  38.         strcat(sx,scount);  //приписываем получившуюся строку к sx
  39.         sx[strlen(sx)-1]='\n';
  40.         fprintf(f2,"%s",sx);  //записываем строку в файл
  41.     }
  42.     if (count==0)
  43.         printf("Файл пуст\n");
  44.     fclose(f1);  //завершаем работу с потоками и файлами
  45.     fclose(f2);
  46.     remove("text.txt");
  47.     rename("temp.txt","text.txt");
  48.     return 0;
  49. }
  50.  
  51.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement