In this program, you will first write to a text file, after writing you will read that text file.
#include<stdio.h>
int main()
{
/* File pointer to hold reference to our file */
FILE *fp,*fp1;
char c;
/*Open file in w (write) mode mode. */
fp=fopen("var.txt","w");
if(!fp)
{printf("file is not present");
exit(1);
}
printf("write a file:");
while(c!='*')
{
/* getche(): read a single character from the keyboard */
c=getche();
/*fputc: write a single character at a time to a given file */
fputc(c,fp);
}
/* after writing closed the file */
fclose(fp);
/*Open file in r (read) mode mode. */
fp1=fopen("var.txt","r");
if(!fp1)
{
printf("file is not open");
/* Unable to open file hence exit */
exit(1);
}
printf("\nread a file:\n");
do{
/*fgetc(): read single character from file */.
c=fgetc(fp1);
printf("%c",c);
}
while(!feof(fp1));
fclose(fp1);
return 0;
}
write a file: Learn from StudyFame read a file: Learn from StudyFame