File Handling Programs
File Handling Programs
By: R
Programs
t Roc
ksta
r
fopen()
#include <stdio.h>
int main()
{
FILE *fp;
char ch;
fp = fopen("file_handle.cpp", "r"); //read only permission
while (1)
{
ch = fgetc(fp);
if (ch == EOF)
break;
printf("%c", ch);
}
file_handle.cpp
#include<stdio.h>
int main(){
int a=10, b=20, c;
c=a+b;
printf("%d",c);
return 0;
}
fprintf()
#include <stdio.h>
int main(){
FILE *fp;
fp = fopen("f2.txt", "w");//opening file and write permission
fprintf(fp, "best of luck for examination...\n");//writing data into file
printf("data inserted successfully");
fclose(fp);//closing file
return 0;
}
f2.txt
best of luck for examination...
fscanf()
#include <stdio.h>
int main(){
FILE *fp;
char buff[255];//creating char array to store data of file
fp = fopen("f3.txt", "r"); //reading
while(fscanf(fp, "%s", buff)!=EOF){
printf("%s ", buff );
}
printf("\nfile reading successfully");
fclose(fp);
return 0;
}
f3.txt
File handling in C enables us to create, update, read, and delete the files stored
on the local file system through our C program. The following operations can be
performed on a file.
example of file handing with emp details
#include <stdio.h>
int main()
{
FILE *fp;
int id; // employee id
char name[30]; //employee name
float salary;
fp = fopen("emp.txt", "w+");/* open for writing and reading both */
if (fp == NULL)
{
printf("File does not exists \n");
return 1;
}
printf("Enter the id\n");
scanf("%d", &id);
fprintf(fp, "Id= %d\n", id);
printf("Enter the name \n");
scanf("%s", name);
fprintf(fp, "Name= %s\n", name);
printf("Enter the salary\n");
scanf("%f", &salary);
fprintf(fp, "Salary= %.2f\n", salary); //500.00
fclose(fp);
return 0;
}
emp.txt
Id= 101
Name= ravi
Salary= 500.00
fputc()
#include <stdio.h>
int main(){
FILE *fp;
fp = fopen("f5.txt", "w");//opening file
fputc('n',fp);//writing single character into file
fclose(fp);//closing file
return 0;
}
f5.txt
n
fgetc()
#include<stdio.h>
int main(){
FILE *fp;
char c;
fp=fopen("f5.txt","r"); //read
while((c=fgetc(fp))!=EOF){
printf("%c",c);
}
fclose(fp);
return 0;
}
fputs()
#include <stdio.h>
int main()
{
FILE *fp;
int main()
{
FILE *fp;
char text[300];
fclose(fp);
return 0;
}