Home > Software design >  I can't print output in another text file
I can't print output in another text file

Time:12-24

int main()
{
    char ch;
    int word_count = 0, in_word = 0;
    char file_name[MAX_LEN];
    /* Pointer for both the file*/
        FILE *fpr, *fpw;
        /* Opening file INPUT.txt in “r” mode for reading */
      start:
      printf("Enter a file name: ");
      scanf("%s", file_name);
      fpr = fopen(file_name, "r");

    /* Ensure INPUT.txt opened successfully*/
    if (fpr == NULL)
        {
        system("cls");
        printf("Could not open the file %s\n", file_name);
        goto start;
        }
          while ((ch = fgetc(fpr)) != EOF) {
          {
            printf("%c",ch);
          }

        if(ch == ' ' || ch == '\t' || ch == '\0' || ch == '\n') {
          if (in_word) {
            in_word = 0;
            word_count  ;
                }
            } else {
            in_word = 1;
        }
      }
        printf("In the file %s:\n", file_name);
    printf("Number of words: %d.\n", word_count);
    /* Opening file OUTPUT.txt in “w” mode for writing*/
    fpw= fopen("OUTPUT.txt", "w");

    /* Ensure OUTPUT.txt opened successfully*/
    if (fpw == NULL)
    {
       puts("Output file cannot be opened");
    }

    /*Read & Write Logic*/
    while ((ch = fgetc(fpr)) != EOF)
    {
        fputc(ch, fpw);
    }

    /* Closing both the files */
    fclose(fpr);
    fclose(fpw);
    return 0;
}

Why is it not printing in the output.txt file? And how can I also print the words in the output file?

There must be a conflict between the while function before printing the input. Or maybe there is something reading before the output then having conflict with another one, when I remove the while function (count words) it shows the product in the output.

CodePudding user response:

You read from fpr until you reach EOF, then try to read from it again.

You need to rewind the file to the beginning for the second fgetc() loop to produce anything.

  •  Tags:  
  • c
  • Related