Click here to Skip to main content
15,890,123 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
So this the code which is giving me problem in Visual C++ 2010 Express. I don't have this problem if a compile it and execute it with gcc in Ubuntu:

FILE * pFile;
char buffer[] = { 'x' , 'y' , 'z' };

pFile = fopen ( "myfile.bin" , "wb" );
fwrite (buffer , 1 , sizeof(buffer) , pFile );
fread(buffer,1,sizeof(buffer),pFile);

printf("%c,%c,%c",buffer[0],buffer[1],buffer[2]);


The problem is that whenever I try to write into the file with the fwrite function it writes me garbage characters.
Because when I try to retrieve them with fread and I print them with printf,contents of the buffer have changed to '='.

Even if I put the file mode to "w" and I open the file with the notepad I see it correctly but there are garbage characters at the end of the file.
So I don't know why this is happening.
The thing is that I have copied this exact example from here and it should be working fine.

http://www.cplusplus.com/reference/cstdio/fwrite/[^]
Posted

1 solution

You program is incorrect. In order to read the written data, you have to (re)position the 'file pointer' at the very beginning of the file. This can simply accomplished by closing the file and then open it again for reading.
C
//...
pFile = fopen ( "myfile.bin" , "wb" );
fwrite (buffer , 1 , sizeof(buffer) , pFile );
fclose(pFile);
fopen ( "myfile.bin" , "rb" );
fread(buffer,1,sizeof(buffer),pFile);
//...



By the way: you should always check the return value of the called functions.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900