Pages

File Management


Dear Learner,

You will get interesting file management program on this page. We create a File for permanent storage of data. C language provides many functions that help us to perform various file operations. Some of the file management functions are given below:


Function Name
Description
fopen()
To create a new file or for opening existing file
fclose()
To close a file
fgetc()
To read a character from a file
fputc()
To write a character to a file
fscanf()
Reads data from a file
fprintf()
Writes data to a file

We use a structure pointer of file type as shown below in C language:

  FILE *fp;

General Syntax to open a file is as under:

  *fp = FILE *fopen(const char *filename, const char *mode);

Where, filename is the name of the file to be opened and mode specifies the purpose of opening the file. The important modes to operate a file are as under:

Mode
Description
r
opens a file for reading
w
opens or create a text file for writing
a
opens a text file for appending content
r+
opens a text file in both reading and writing mode
w+
opens a text file in both reading and writing mode
a+
opens a text file in both reading and writing mode


* * * * *

C Programming File Management Programs


Execute following C programs to learn more file management related functionalities.


Sample C File Management Programs


C Program to read one character from a test.txt file.

Note: Your source file and test.txt file must be in a same folder.

#include<stdio.h>
int main(){

 FILE *fp;
 char ch;

 //code to open file for reading
 fp=fopen("test.txt","r");
 
 if(fp==NULL){
     printf("File error");
     exit(0);
 }

 //code to read a character
 ch fgetc(fp);
  
 printf("%c",ch);
 fclose(fp);
 
 return 0;
}

* * *


#include<stdio.h>
int main(){

 FILE *fp;
 char ch;

 fp=fopen("test.txt","r");
 
 if(fp==NULL){
printf("File error");
exit(0);
 }
 
 ch = fgetc(fp);

 while(ch != EOF){
printf("%c",ch);  
ch=fgetc(fp);
 }
 fclose(fp);
 
 return 0;
}




4 comments: