Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 296
  • Last Modified:

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);

0
zizi21
Asked:
zizi21
  • 5
  • 3
1 Solution
 
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
 
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
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

 
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
 
spoxoxCommented:
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
 
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

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 5
  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now