Programs on Files
Example Program 1 using write mode to create new file and to write the data in file:
#include<stdio.h>
void main(){
int i;
char name[15];
FILE *fp;
fp=fopen("data1.txt","w");
printf("Input an integer");
scanf("%d",&i);
printf("Enter your name:");
scanf("%s",name);
fprintf(fp,"%d\n%s",i,name);
fclose(fp);
}
Output:
data1.txt
Example Program 2 using read mode to read the data from file:
#include<stdio.h>
void main() {
int i;
char name[15];
FILE *fp;
fp=fopen("data1.txt","r");
fscanf(fp,"%d%s",&i,name);
printf("The integer in data1.txt is %d\n",i);
printf("The String in data1.txt is %s",name);
fclose(fp);
}
Output:
Example Program 3 using append mode to add the data in the existing file:
#include<stdio.h>
void main() {
char name[15];
FILE *fp;
fp=fopen("data2.txt","a");
printf("Enter ur name:");
scanf("%s",name);
fprintf(fp,"%s",name);
fclose(fp);
fp=fopen("data2.txt","r");
if(fscanf(fp,"%s",name))
printf("%s",name);
fclose(fp);
}
Output:
data2.txt
After appending:
