[Subject Prev][Subject Next][Thread Prev][Thread Next][Subject Index][Thread Index]

Re: Re: Re: Fw: Infinite Joy Ride(example)



hai,

It is the simple program that is given as an example to 
illustrate random file handling in "C For Linux Programming"

The program works well if numeric values are given.If I 
give non numeric value say 'A'.It goes for infinite joy 
ride and the value of offset still remains at the value 
that I have given before giving the non numeric value.

After invalid input scanf fails to scan anymore and if I 
try to print the value of offset in if and else if prints 
the address of offset not the value.

kamesh jayachandran
//source starts here
#include<stdlib.h>
#include<stdio.h>
#define MAX 50
int main(void)
{
FILE *fp;
int data,count,array[MAX];
long offset;
for(count=0;count<MAX;count++)
array[count]=count*10;
if((fp=fopen("pp","wb"))==NULL)
{
fprintf(stderr,"Error opening File \n");
exit(1);
}
if(fwrite(array,sizeof(int),MAX,fp)!=MAX)
{
fprintf(stderr,"Error in writing data to the File\n");
exit(1);
}
fclose(fp);
if((fp=fopen("pp","rb"))==NULL)
{
fprintf(stderr,"Error in opening File\n");
exit(1);
}
while(1)
{
printf("\nEnter element to read,0-%d,-1 to quit: ",MAX-1);
scanf("%ld",&offset);
if(offset<0)
{
printf("In if %ld",offset);
break;
}
else if(offset>MAX-1)
{
printf("In else if %ld",offset);
continue;
}
if(fseek(fp,(offset*sizeof(int)),0)!=0)
{
fprintf(stderr,"Error using fseek\n");
exit(1);
}
fread(&data,sizeof(int),1,fp);
printf("\nElement %ld has value %d",offset,data);
}
fclose(fp);
return 0;
}
//source ends here