Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

i cant print output in another text file please help me

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 thank you! 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.

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading