Question

I'm trying to read numbers from a file named part_1.txt which contains the following data:

101
102
103
104
105
106
107
108
109

This is the code i'm working with:

#include <stdio.h>

int main()
{

FILE *handle_in1 = fopen("part_1.txt", "r");
FILE *handle_in2 = fopen("part_2.txt", "r");
FILE *handle_out = fopen("parts.txt", "w");

int scan;

if(handle_in1 == NULL || handle_in2 == NULL)
{
printf("File(s) could not be handled.");
}

else
{
while(fscanf(handle_in1, "%d", &scan) != EOF)
{
    fscanf(handle_in1, "%d", &scan);
    printf("Number is %d\n", scan);
}
}
return 0;

}

The code should print out on the screen every value that is stored in the file, until End Of the File. Instead it prints out every other value (and last value), like this:

Number is 102
Number is 104
Number is 106
Number is 108
Number is 109 

What is wrong in this code?

I edited this question since i cannot post answer until 8 hours. The following version is the new version:

#include <stdio.h>

int main()
{

FILE *handle_in1 = fopen("part_1.txt", "r");
FILE *handle_in2 = fopen("part_2.txt", "r");
FILE *handle_out = fopen("parts.txt", "w");

int scan;

if(handle_in1 == NULL || handle_in2 == NULL)
{
printf("File(s) could not be handled.");
}

else
{
fscanf(handle_in1, "%d", &scan);
    while(fscanf(handle_in1, "%d", &scan) != EOF)
    {
    printf("Number is %d\n", scan);
    }
}
return 0;

}

this edited version of the program gives me the values: 102, 103, 104, 105, 106, 107, 108 and 109. if i edit the txt file and put one extra 101 on top of the txt file, then it gives the values all the way from 101 to 109 so it must skip the first number. Why it does that i have no idea...

Was it helpful?

Solution

You are doing something wrong over here:

while(fscanf(handle_in1, "%d", &scan) != EOF)
{
    fscanf(handle_in1, "%d", &scan);
    printf("Number is %d\n", scan);
}

The solution is:

Use only one scanf in an iteration of the loop.

So it will become (this is one solution):

while(fscanf(handle_in1, "%d", &scan) != EOF)
{
    printf("Number is %d\n", scan);
}

OTHER TIPS

The solution to your second problem is that you have to remove the first fscanf line after the else and right before the while like so

    FILE *handle_in1 = fopen("part_1.txt", "r");
    int scan;

    if(handle_in1 == NULL ){
            printf("File(s) could not be handled.");
    } else  {
    /*      fscanf(handle_in1, "%d", &scan);*/ // this line is unnecessary
            while(fscanf(handle_in1, "%d", &scan) != EOF) {
                printf("Number is %d\n", scan);
            }
    }
    return 0;

that fscanf was removing the first line of your file.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top