C/how to use fwrite()
Expert: Prince M. Premnath - 6/6/2007
QuestionHi,sir: Can you tell me why dont write "R" in simple follow code? im confused why fwrite function cant write 2 s.ch?!!
please help me:
#include <stdio.h>
#include<conio.h>
struct mystruct
{
int i;
char ch;
};
int main()
{
FILE *stream;
struct mystruct s,s1;
clrscr();
if ((stream = fopen("TEST.dat", "wb ")) == NULL) /* open file TEST.$$$ */
{
fprintf(stderr, "Cannot open output file.\n");
return 1;
}
s.i = 0;
s.ch = 'v';
fwrite(&s, sizeof(s), 1, stream); /* write struct s to file */
s1.i=11;
s1.ch='R';
fwrite(&s1, sizeof(s1), 1, stream);
fclose(stream);
stream = fopen("TEST.dat", "w b");
rewind(stream);
while(!feof(stream)){
fread(&s, sizeof(sizeof( mystruct)), 1, stream);
printf("\nstream %c",s.ch);
};
fclose(stream);
getch(); /* close file */
return 0;
}
AnswerDear Mr Ben!
Upon verifying your code i found lot of Bugs in your code ,
> stream = fopen("TEST.dat", "wb"); Opening again the file using wb mode will erase the contents of the file and open it as a new file so it should be avoided instead i have used "rb" mode.
> fread(&s, sizeof(sizeof( mystruct)), 1, stream); Now take a look at this statement siezof(sizeof(mystruct)) actually it should be like this sizeof(s) , its well enough
I had made some changes over your code , now its working pretty fine!
#include<stdio.h>
#include<conio.h>
struct mystruct
{
int i;
char ch;
};
int main()
{
FILE *stream;
struct mystruct s;
clrscr();
if ((stream = fopen("TEST.dat", "wb+ ")) == NULL) /* open file TEST.$$$ */
{
fprintf(stderr, "Cannot open output file.\n");
return 1;
}
s.i = 0;
s.ch = 'v';
fwrite(&s, sizeof(s), 1, stream); /* write struct s to file */
s.i = 1;
s.ch = 'R';
fwrite(&s, sizeof(s), 1, stream);
fclose(stream);
stream = fopen("TEST.dat", "rb+");
rewind(stream);
while(fread(&s, sizeof(s), 1, stream))
{
printf("\n %c %d",s.ch , s.i);
}
fclose(stream);
getch();
return 0;
}
Note:
If you need any explanation over this code please dont hesitate to ask a follow up question
Thanks and Regards
Prince M. Premnath