Thread: Printing a file

  1. #1
    Registered User
    Join Date
    Oct 2010
    Posts
    11

    Printing a file

    I had written the following code which does the following:
    It takes in a series of integers as input.
    It prints all the integers that come before 42 has been input (assumes that the user inputs 42 at some point of time) to the screen as well as to a file named out.txt.
    The printing to the screen is done by reading from the out.txt file.

    While printing to the screen, I found that the last integer was being printed twice (on screen) even though the output of the text file is correct. Why is this ?

    Code:
    #include <stdio.h>
    int main()
    {
        FILE *fp1;
        fp1 = fopen("out.txt", "w");
        int n,i;
        do
        {
            scanf("%d", &n);
            if(n == 42)
                 break;
            fprintf(fp1, "%d\n", n);
        }while(n!=42);
        
        fclose(fp1);
        
        fp1 = fopen("out.txt", "r");
        while(!feof(fp1))
        {
             fscanf(fp1, "%d", &n);
             printf("%d\n", n);
        }
             
        fclose(fp1);
        getch();
        return 0;
    }

  2. #2
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    That's the unfortunate way that feof() works. It's weird. I wouldn't use it. Use the return from fscanf(), instead. If it's greater than zero, it's still getting data.

  3. #3
    Registered User
    Join Date
    Oct 2010
    Posts
    11
    So, modifying this part will work ?

    Code:
     
    while(fscanf(fp1, "%d", &n) > 0)
             printf("%d\n", n);
    How does feof work exactly ?

  4. #4
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    This explains it better than I can:
    http://www.gidnetwork.com/b-58.html

    I just a little (double) test of feof(), and OF COURSE, it worked just fine without any double checking. Go figure!

    C'est la vie!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Formatting a text file...
    By dagorsul in forum C Programming
    Replies: 12
    Last Post: 05-02-2008, 03:53 AM
  2. gcc link external library
    By spank in forum C Programming
    Replies: 6
    Last Post: 08-08-2007, 03:44 PM
  3. Inventory records
    By jsbeckton in forum C Programming
    Replies: 23
    Last Post: 06-28-2007, 04:14 AM
  4. System
    By drdroid in forum C++ Programming
    Replies: 3
    Last Post: 06-28-2002, 10:12 PM
  5. simulate Grep command in Unix using C
    By laxmi in forum C Programming
    Replies: 6
    Last Post: 05-10-2002, 04:10 PM

Tags for this Thread