A file is sequence of bytes which stores data. It is made for permanent storage of data. It is known to be a ready made structure.
In this program we will learn how to create a file along with how to write and read characters from it.
WRITE
#include <stdio.h>;
int main(){
int ch;
FILE* fp;
fp=fopen("Aryan.txt","w");
if(fp==NULL){
printf("error");
exit(1);
}
else{
printf("enter value");
scanf("%d",&ch);
fprintf(fp,"%d",ch);
printf("Element added");
fclose(fp);
}
}
Output
READ
#include <stdio.h>;
int main(){
int ch;
FILE* fp;
fp=fopen("Aryan.txt","r");
if(fp==NULL){
printf("error");
exit(1);
}
else{
fscanf(fp,"%d",&ch);
printf("element is %d",ch);
fclose(fp);
}
}
Output