Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #include <locale.h>
- #define n 80
- int main()
- {
- setlocale(LC_ALL,"Rus");
- FILE *f1,*f2;
- int count;
- char s[n],sx[n],*p,scount[n];
- if (!(f1=fopen("text.txt","r"))) //проверяем открылся ли файл
- {
- printf("Не удалось открыть файл\n");
- return 1;
- }
- if (!(f2=fopen("temp.txt","w"))) //проверяем создался ли временный файл
- {
- printf("Не удалось создать файл\n");
- fclose(f1);
- return 2;
- }
- while((p=fgets(s,n,f1))!= NULL) //построчно читаем данные из файла
- {
- count=0;
- strcpy(sx,s); //создаём копию строки, т.к. команда strtok добавляет \0 в строку, с которой взаимодействует. затем будем в файл будем записывать уже копию
- p=strtok(s," ");
- while(p!=NULL) //считаем кол-во слов в строке
- {
- count++;
- p=strtok(NULL," ");
- }
- sprintf(scount,"(%d) ",count); //переводим число в строку
- p=strchr(sx,'\n'); //убираем \n, который приписался к sx в strcpy(sx,s)
- if (p)
- *p=' ';
- strcat(sx,scount); //приписываем получившуюся строку к sx
- sx[strlen(sx)-1]='\n';
- fprintf(f2,"%s",sx); //записываем строку в файл
- }
- if (count==0)
- printf("Файл пуст\n");
- fclose(f1); //завершаем работу с потоками и файлами
- fclose(f2);
- remove("text.txt");
- rename("temp.txt","text.txt");
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement