Page 1 of 1

problem with C

Posted: Thu Nov 18, 2004 7:54 pm
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?

Re:problem with C

Posted: Fri Nov 19, 2004 12:15 am
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)

Re:problem with C

Posted: Fri Nov 19, 2004 12:50 am
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.

Re:problem with C

Posted: Fri Nov 19, 2004 3:03 am
by jicama
cxnew:
thanks, I Know, that must use binary mode to open file.