-
June 12th, 2013, 12:31 PM
#1
Binary file-question!!!
Hi!!!I need some help!!!
I have written the following code:
Code:
#include <stdio.h>
struct info
{
float mo;
int age;
}m;
int main()
{
int il;
FILE *fp;
fp=fopen("sx.txt","rb");
if (fp==NULL){
printf("Problem!!!\n");
exit(0);
}
fseek(fp,4,0);
fread(&m,sizeof(struct info),1,fp);
printf("Age:%d\n",m.age);
rewind(fp);
fread(&m,sizeof(struct info),1,fp);
printf("Age:%d\n",m.age);
return 0;
}
and put at the file the following numbers:
5 18
8.5 21
10 20
3 18
6 19
The first printf("Age:%d\n",m.age); does not give me the right result(19)..Why????
-
June 12th, 2013, 12:57 PM
#2
Re: Binary file-question!!!
Your file is in plain-text format but you are reading it as if it is a binary-coded format. That's why you get what looks to be junk.
-
June 12th, 2013, 01:04 PM
#3
Re: Binary file-question!!!
so...what could I change???
-
June 12th, 2013, 01:09 PM
#4
Re: Binary file-question!!!
Depends upon how it should work . Either:
1) Change the code to read the file as plain-text, or
2) Change the file so the data is binary-coded.
-
June 12th, 2013, 01:25 PM
#5
Re: Binary file-question!!!
My file is binary-coded,I had written this code:
Code:
#include <stdio.h>
struct info
{
float mo;
int age;
}students[5];
int main()
{
FILE *fp;
int i;
for (i=0; i<5; i++){
scanf("%f%d",&students[i].mo,&students[i].age);
}
fp=fopen("sx.txt","wb");
fwrite(students,sizeof(struct info),5,fp);
fclose(fp);
return 0;
}
:/
-
June 12th, 2013, 01:32 PM
#6
Re: Binary file-question!!!
Why does it not give the right output???
-
June 12th, 2013, 01:40 PM
#7
Re: Binary file-question!!!
Code:
int main()
{
int il;
FILE *fp;
fp=fopen("sx.txt","rb");
if (fp==NULL){
printf("Problem!!!\n");
exit(0);
}
fseek(fp,4,0);
fread(&m,sizeof(struct info),1,fp);
printf("Age:%d\n",m.age);
rewind(fp);
fread(&m,sizeof(struct info),1,fp);
printf("Age:%d\n",m.age);
return 0;
}
Look at the '4' in the fseek call. You should be seeking a multiple of sizeof(info).
Edit: And don't give files a 'txt' extension unless they are human-readable. It only confuses things
-
June 12th, 2013, 01:59 PM
#8
Re: Binary file-question!!!
Nice!!!!Thank you very much!!!!!!!
Tags for this Thread
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|