• C

Urgent:fread

hi,

i am doing this with fread and i get ??? marks..could anyone pls help...thanks

char *t;
t=(char *)malloc(28);

      fread(t,sizeof(char),28,fp);
t[9]='\0';
      
      printf("%s\n",t);

zizi21Asked:
Who is Participating?

Improve company productivity with a Business Account.Sign Up

x
 
spoxoxConnect With a Mentor Commented:
Still works for me. A couple of other points.

1) Note the alternate use of malloc on line 1.

2) Definitely want to make sure file is opened successfully: lines 3...8

3) Browse the file to make sure it's not empty.

4) Note the change in fread in line 10. The second parameter is the size of each element to be read. It should not be sizeof(t), as t is a pointer - unless you are reading pointers. It looks like you want to read characters.
char *t = malloc(28 * sizeof(char));
 
FILE *fp;
fp = fopen("dat\\test.dat", "r");
if (fp==NULL) {
  printf("Error: can't open file.");
  return -1;
}
 
fread(t, sizeof(char), 8, fp);
t[9]='\0';
printf("%s\n",t);

Open in new window

0
 
spoxoxCommented:
What file are you trying to read? Your code will read from a file. Make sure you have successfully opened a file for reading.
char t[10];
 
FILE *fp;
fp = fopen("dat\\test.dat", "r");
if (fp==NULL) {
  printf("Error: can't open file.");
  return -1;
}
 
fread(t,sizeof(t),8,fp);
t[9]='\0';
printf("%s\n",t);

Open in new window

0
 
spoxoxCommented:
Hey, the question changed!
0
Get 10% Off Your First Squarespace Website

Ready to showcase your work, publish content or promote your business online? With Squarespace’s award-winning templates and 24/7 customer service, getting started is simple. Head to Squarespace.com and use offer code ‘EXPERTS’ to get 10% off your first purchase.

 
zizi21Author Commented:
hi..you are right....i was trying few ways....i was able to edit it..dont worry...i would accept the solution if it works....
0
 
zizi21Author Commented:
hi, it doesn't work..
the reason i edited the question is because i found any link here which teaches you with malloc..with the current way, you get segementation faults, bus errors...i would go with the edited question then...thanks..
0
 
zizi21Author Commented:
hi there,

you are right...when i was doing make clean..not targets was deleted...thats why..it works..thank you...


0
 
zizi21Author Commented:
excellent!
0
 
zizi21Author Commented:
hi ,

what do you mean by browse the file...how do you do that?
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.