Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

FILE I/O in C infinite loop

  1. Apr 21, 2012 #1
    I am supposed to read from 2 text files containing numbers in ascending order, then output the all the numbers in ascending order to an output file, For some reason my output file is reaching an infinite loop it orders the numbers correctly but the last number reapeats forever. I am thinking it has to do with my conditional statements such as feof, when maybe I should be using EOF. Can someone help, thanks.


    Code (Text):

    #include <stdio.h>
    #include <stdlib.h>

    int main(int argc, char* argv[])
    {
    FILE *i1;
    FILE *i2;
    FILE *o;

    int num1, num2;

        if(argc!=4)
        {  
        printf("Error in valid number of arguments\n");
        exit(1);
        }

       
        if((i1=fopen(argv[1], "r"))==NULL)
        {
        printf("Failed to open First File\n");
        exit(1);
        }

       
        if((i2=fopen(argv[2],"r"))==NULL)
        {
        printf("Failed to open Second File\n");
        exit(1);
        }


        if((o=fopen(argv[3],"w"))==NULL)
        {
        printf("Failed to open Third File\n");
        exit(1);
        }


        while(!feof(i1) && !feof(i2))
        {
        fscanf(i1,"%d",&num1);
        fscanf(i2,"%d",&num2);

            if(num1<=num2)
            fprintf(o,"%d\n",num1);
            else
            fprintf(o,"%d\n",num2);
        }

        if(!feof(i1))  
        {
            fprintf(o,"%d\n",num1);
            while(!feof(i1))
            {
            fscanf(i1,"%d",&num1);
            fprintf(o,"%d\n",num1);
            }  
        }



        if(!feof(i2))
        {  
        fprintf(o,"%d\n",num2);
            while(!feof(i2))
            {
            fscanf(i1,"%d",&num2);
            fprintf(o,"%d\n",num2);
            }

        }



    fclose(i1);
    fclose(i2);
    fclose(o);
    return 0;

    }
     
     
  2. jcsd
  3. Apr 21, 2012 #2

    rcgldr

    User Avatar
    Homework Helper

    The problem is that you're reading from i1 in the last loop (while checking for eof from i2).
     
  4. Apr 21, 2012 #3
    I love you very much :) may you be a blessed and happy man for eternity.
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook




Similar Discussions: FILE I/O in C infinite loop
  1. C++ Simple File I/O (Replies: 12)

  2. C file I/O (Replies: 3)

  3. FILE I/O in an IDE (Replies: 1)

  4. C++ file i/o (Replies: 7)

Loading...