Vla_DOS

Untitled

Jan 12th, 2023
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.09 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4.  
  5. #define WORD_SIZE 256
  6. #define WORD_MASK "%255s"
  7.  
  8. #define INPUT_FILE "input.txt"
  9. #define OUTPUT_FILE "output.txt"
  10.  
  11. void Write(char* path){
  12.     // строка для записи
  13.     char * message = "text file text file";
  14.     // файл для записи
  15.     // запись в файл
  16.     FILE *fp = fopen(path, "w");
  17.     if(!fp)
  18.     {
  19.         printf("Error occured while opening file\n");
  20.         return 1;
  21.     }
  22.     // записываем строку
  23.     fputs(message, fp);
  24.  
  25.     fclose(fp);
  26. }
  27.  
  28. void Read(char* path){
  29.     // буфер для считавания данных из файла
  30.     char buffer[256];
  31.     // чтение из файла
  32.     FILE *fp = fopen(path, "r");
  33.     if ( ! ( fp = fopen(path, "r") ) ) {
  34.         fprintf(stderr, "Can't open %s for output!\n", path);
  35.         exit(1);
  36.     }
  37.     // пока не дойдем до конца, считываем по 256 байт
  38.     while((fgets(buffer, 256, fp))!=NULL)
  39.     {
  40.         printf("%s", buffer);
  41.     }
  42.  
  43.     fclose(fp);
  44. }
  45.  
  46. void Replace(){
  47.     FILE *fin, *fout;
  48.         if ( ! ( fin = fopen(INPUT_FILE, "r") ) ) {
  49.         fprintf(stderr, "Can't open %s for output!\n", INPUT_FILE);
  50.         exit(1);
  51.     }
  52.     if ( ! ( fout = fopen(OUTPUT_FILE, "w") ) ) {
  53.         fprintf(stderr, "Can't open %s for output!\n", OUTPUT_FILE);
  54.         exit(1);
  55.     }
  56.     char wordToRemove[WORD_SIZE], wordToInsert[WORD_SIZE], currentWord[WORD_SIZE];
  57.     printf("Word to remove: ");
  58.     scanf(WORD_MASK, wordToRemove);
  59.     printf("Word to insert: ");
  60.     scanf(WORD_MASK, wordToInsert);
  61.  
  62.     while ( fscanf(fin, WORD_MASK, currentWord) == 1 ) {
  63.         if ( fprintf(fout, "%s ", ( strcmp(currentWord, wordToRemove) == 0) ? wordToInsert : currentWord) < 1 ) {
  64.             fprintf(stderr, "Can't write to output file!\n");
  65.             exit(1);
  66.         }
  67.     }
  68.     fclose(fin);
  69.     fclose(fout);
  70.  
  71. }
  72. int main(void){
  73.  
  74.     Read(INPUT_FILE);
  75.     printf("\n");
  76.     Write(INPUT_FILE);
  77.  
  78.     Replace();
  79.     Read(OUTPUT_FILE);
  80.  
  81.  
  82.     exit(0);
  83. }
  84.  
Advertisement
Add Comment
Please, Sign In to add comment