Here's my problem.
I'm trying to write info to a bin file, consider the following piece of code:

FILE *fp = fopen("banco\\banco.bin", "ab");

	char buffer[22];

	sprintf(buffer, "55555555 111111 11111");

	fwrite(buffer, sizeof(char), 22, fp);

	fclose(fp);

when I run this it writes to the file that line twice

when I print it I get
55555555 111111 11111
55555555 111111 11111

and if I run it again adding a line like
44444444 111111 11111

it will output
55555555 111111 11111
44444444 111111 11111
44444444 111111 11111

Why is it happening any idea ?

Please post a complete program that exhibits the problem.

To test the problem I just wrote this part on my main ... this is a complete program ... the other part would be this code

fp = fopen("banco\\banco.bin", "rb");

	while(!feof(fp))
	{
		fread(buffer, sizeof(char), 22, fp);
		printf("%s\n", buffer);
	}

	fclose(fp);

to print the file

Well, there you go. Using feof() as a loop condition will most likely result in processing the last line of the file twice. This is because feof() only returns true after you've tried and failed with an input request like fread. Use the result of fread as your condition instead, and I bet it'll work just fine.

Edited 5 Years Ago by Narue: n/a

Well, there you go. Using feof() as a loop condition will most likely result in processing the last line of the file twice. This is because feof() only returns true after you've tried and failed with an input request like fread. Use the result of fread as your condition instead, and I bet it'll work just fine.

Thanks ... I was stupid ... I used that for txt files testing fgets for NULL .. and didn't think of it here ... thx a lot

This article has been dead for over six months. Start a new discussion instead.