Credits

Sunday, March 15, 2009

C's File and Input Stream: Keyboard Reading

We have to be however flexible in writing our source codes. Thus, to improve the codes on writing to a file, we can use the fscanf() to read keyboard inputs and write them into our file.

Check the sample program.

Click the link to view/hide more.

[+/-] show/hide

#include stdio.h /*enclose this in <> */
main()
{
FILE *MYFILE;
char name[30];
if ((MYFILE=fopen("mysample.txt","w"))!=NULL) /*creating a file named mysample.txt*/
{
printf("Enter your fullname: ");
fscanf(stdin,"%s",&name);
fprintf(MYFILE,"%s",name);
fclose(MYFILE); /*closing the file*/
}
else

{printf("There is an error writing mysample.txt!\n");
getche();clrscr();

if((MYFILE=fopen("mysample.txt","r"))!=NULL)
{
if ((fgets(name,sizeof(name),MYFILE))!=NULL)
{
printf("Your name is %s",name);
fclose(MYFILE);
}
else
printf("Error reading mysample.txt!\n");
}

else
printf("Error opening mysample.txt!\n");
getche();
}

AddThis