On Jan 10, 2008 8:57 AM, 王磊 <[EMAIL PROTECTED]> wrote:
> I use fscnaf like the:
> FILE *fptr;
> int a;
> fptr = fopen("input","r");
> if ( fscanf(fptr,"%d",a) ) {
> printf("%d",&a);
>
> }
>
> else printf("wrong");
> fclose(fptr);
>
> But it can not run successfully.
(1) You're not checking the return from the fopen() call
(2) You're not checking the return from the fscanf() call properly.
(3) You do nothing if the fscanf() fails.
(4) You're printing the wrong thing.
FILE* fp;
int a, r;
if ( (fp= fopen("input", "r") ){
if ( (r = fscanf(fp, "%d", a) == 1){
printf("%d read in\n", a);
}else{
fprintf(stderr, "Unable to scan input. %d items read\n", r);
}
}else{
fprintf(stderr, "Unable to open file\n");
}
(Not compiled - there may be syntax errors in there.)
--
PJH
http://shabbleland.myminicity.com