• Some users have recently had their accounts hijacked. It seems that the now defunct EVGA forums might have compromised your password there and seems many are using the same PW here. We would suggest you UPDATE YOUR PASSWORD and TURN ON 2FA for your account here to further secure it. None of the compromised accounts had 2FA turned on.
    Once you have enabled 2FA, your account will be updated soon to show a badge, letting other members know that you use 2FA to protect your account. This should be beneficial for everyone that uses FSFT.

Bug with my C code

TheJokerV

Weaksauce
Joined
Mar 23, 2007
Messages
81
Basically I'm writing a C program to read in a list of numbers from a file and output their binary mirrors and number of bit 1's in their binary representation. The file has a 32 bit unsigned decimal number on each line and the number of lines has not been specified. So I wrote the following code:
Code:
#include <stdio.h>

#include "bits.h"



int main(int argc, char *argv[])

{

	unsigned int num;

	

	if(argc != 2){

		printf("Invalid Arguement(s)\n");

		return 0;

	}

	FILE *fp;

	fp = fopen(argv[1], "r");

	

	printf("Binary Mirror:   Number of bit-1's\n");

	while(!feof(fp)){

		fscanf(fp, "%u", &num);

		printf("%u       %u\n", bin_mirror(num), pop_count(num));

	}
	fclose(fp);
	return 0;

}
And the program is doing what it should except that it reads the last line twice. The output to a sample looks like:
Binary Mirror: Number of bit-1's
510274632 13
2147483648 1
1744830464 3
2994733056 5
981991424 6
3231383552 7
1412714496 8
2411032064 15
476721824 12
4287846876 21
4287846876 21
Where the last line is repeated. There should be only 10 lines (11 if including header) printed out. I cant figure out where the bug is. The while loop should be broken when the end of the file is reached but for some reason the last line is read twice. Any ideas?
 
feof only returns nonzero (indicating eof) if the previous read operation read and failed. Therefore, when you read the last line, feof is not set to 'true' (end of file reached), and so when you go back to the top of the while loop, the condition has not been met and the read at that point will make the next call to feof return non-zero.

You probably want to do something like this instead:

Code:
	while(EOF != fscanf( fp, "%u", &num ))
        {
		printf("%u       %u\n", bin_mirror(num), pop_count(num));
	}
 
Back
Top