problem with C

Programming, for all ages and all languages.
Post Reply
jicama

problem with C

Post by jicama »

#include<stdio.h>
int main()
{
FILE *fp;
char xp,test;
test=0;
printf("please input a number:\n");
scanf("%d",&test);
if((fp=fopen("zhou.h","w"))!=NULL)
??? fwrite(&test,sizeof(char),1,fp);
fclose(fp);
if((fp=fopen("zhou.h","r"))!=NULL)
fread(&xp,sizeof(char),1,fp);
printf("xp=%d\n",xp);
printf("test=%d\n",test);
fclose(fp);
return 0;
}
please run this program, if input 26, that the value of 'xp' is zero, why?
cxsnew

Re:problem with C

Post by cxsnew »

please try to use the following instruction when open the file:
if((fp=fopen("zhou.h","w+b"))!=NULL) and
if((fp=fopen("zhou.h","r+b"))!=NULL)
User avatar
Candy
Member
Member
Posts: 3882
Joined: Tue Oct 17, 2006 11:33 pm
Location: Eindhoven

Re:problem with C

Post by Candy »

I locked voting since this isn't a poll but a question.

The answer imo is that you read an int, store it into a char, write it into a file without checking whether that was a success, then read it back without checking whether THAT was a success either, and then print the result.

Answer is to check more often (after compiling your code it segfaulted here, after putting in the checks it more or less worked, after converting it to longs or ints it just works) and to use the right types for the things you read. You cannot read an int to a char.
jicama

Re:problem with C

Post by jicama »

cxnew:
thanks, I Know, that must use binary mode to open file.
Post Reply