File Handling
File Handling
➢ A file represents a sequence of bytes on the disk where a group of related data is stored.
➢ File is created for permanent storage of data. It is a readymade structure.
➢ In C language, we use a structure pointer of file type to declare a file.
➢ C provides a number of functions that helps to perform basic file operations. Following
are the functions:
➢
Function description
Types of Files :
When dealing with files, there are two types of files you should know about:
1. Text files
2. Binary files
1. Text files
➢ They take minimum effort to maintain, are easily readable, and provide the least security
and takes bigger storage space.
2. Binary files
➢ They can hold a higher amount of data, are not readable easily, and provides better
security than text files
Widely used file format and can be opened Developed especially for an application and
using any simple text editor. may not be understood by other applications.
Operations in FILE :
➢ A File can be used to store a large volume of persistent data. Following are some
operations which can be performed in a file.
1. Creation of a file
2. Opening a file
3. Reading a file
4. Writing to a file
5. Closing a file
➢ Whenever you want to work with a file, the first step is to create a file. A file is nothing
but space in a memory where data is stored.
FILE *fp;
fp = fopen ("file_name", "mode");
In the above syntax, the file is a data structure which is defined in the standard library.
Example 1:
#include <stdio.h>
void main()
{
FILE *fp;
fp =fopen ("data.txt", "w");
}
Output:
File is created in the same folder where you have saved your code.
Example 2:
You can specify the path where you want to create your file
#include <stdio.h>
int main() {
FILE *fp;
fp =fopen ("D://data.txt", "w");
}
➢ The fopen() function is used to create a new file or to open an existing file.
➢ If the file is not present on the system, then it is created and then opened.
4
➢ If a file is already present on the system, then it is directly opened using this function.
Mode in File
➢ Whenever you open or create a file, you have to specify what you are going to do with the
file. A file in 'C' programming can be created or opened for reading/writing purposes. A
mode is used to specify whether you want to open a file for any of the below-given
purposes.
Following are the different types of modes in 'C' programming which can be used while
working with a file.
Mode Description
For example, in the following program, if “test.txt” already exists, its contents are removed
and “VSSUT” is written to it.
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE*fp = fopen("test.txt", "w");
if(fp == NULL)
{
puts("Couldn't open file");
exit(0);
}
else
{
fputs("VSSUT", fp);
puts("Done");
fclose(fp);
}
return 0;
}
The above behaviour may lead to unexpected results. If programmer’s intention was to create
a new file and a file with same name already exists, the existing file’s contents are
overwritten.
The latest C standard C11 provides a new mode “x” which is exclusive create-and-open
mode. Mode “x” can be used with any “w” specifier, like “wx”, “wbx”. When x is used with
w, fopen() returns NULL if file already exists or could not open.
#include <stdlib.h>
int main()
{
FILE*fp = fopen("test.txt", "wx");
if(fp == NULL)
{
puts("Couldn't open file or file already exists");
exit(0);
}
else
{
fputs("VSSUT", fp);
puts("Done");
fclose(fp);
}
return 0;
}
❖ Closing a File :
➢ The fclose() function is used to close an already opened file.
General Syntax :
fclose( file_ptr);.
Example:
FILE *fp;
fp =fopen ("data.txt", "r");
fclose (fp);
➢ In 'C' programming, files are automatically close when the program is terminated.
7
• Writing to a File:
• fputc()
-The is used to writing a character to a file
Syntax:
fputc(character,file_pointer);
EXAMPLE :
#include <stdio.h>
main()
{
FILE *fp;
fp = fopen("/tmp/test.txt", "w+");
fprintf(fp, "This is testing for fprintf...\n");
fputs("This is testing for fputs...\n", fp);
fclose(fp);
}
When the above code is compiled and executed, it creates a new file test.txt in /tmp directory
and writes two lines using two different functions. In C, when you write to a file, newline
characters '\n' must be explicitly added.
EXAMPLE1:
#include <stdio.h>
int main()
{
inti;
FILE * fptr;
char fn[50];
char str[] = "HELLO VSSUT\n";
fptr = fopen("fputc_test.txt", "w"); // "w" defines "writing mode"
for (i = 0; str[i] != '\n'; i++)
{
/* write to file using fputc() function */
fputc(str[i], fptr);
}
fclose(fptr);
return 0;
}
The above program writes a single character into the fputc_test.txt file until it reaches the
next line symbol "\n" which indicates that the sentence was successfully written. The process
is to take each character of the array and write it into the file.
1. In the above program, we have created and opened a file called fputc_test.txt in a
write mode and declare our string which will be written into the file.
2. We do a character by character write operation using for loop and put each character
in our file until the "\n" character is encountered then the file is closed using the
fclose() function.
• fputs () Function:
Example:
#include <stdio.h>
intmain() {
FILE * fp;
fp = fopen("fputs_test.txt", "w+");
fputs("This is demo of fputs,", fp);
fputs("We don't need to use for loop\n", fp);
fputs("Easier than fputc function\n", fp);
fclose(fp);
return (0);
}
OUTPUT:
1. In the above program, we have created and opened a file called fputs_test.txt in a
write mode.
2. After we do a write operation using fputs() function by writing three different strings
• fprintf()Function:
-works just like printf() except that its first argument is a file pointer.
Syntax:
fprintf(file_pointer, “control string”, list);
9
Example:
#include <stdio.h>
intmain() {
FILE *fptr;
fptr = fopen("fprintf_test.txt", "w"); // "w" defines "writing mode"
/* write to file */
fprintf(fptr, "Hello VSSUT\n");
fclose(fptr);
return 0;
}
OUTPUT:
Hello VSSUT
1. In the above program we have created and opened a file called fprintf_test.txt in a
write mode.
2. After a write operation is performed using fprintf() function by writing a string, then
the file is closed using the fclose() function.
#include<stdio.h>
#include<stdlib.h>
int main()
{
int num;
FILE *fptr;
fptr = fopen("C:\\program.txt","w");
if(fptr == NULL)
{
printf("Error!");
exit(1);
}
fprintf(fptr,"%d",num);
fclose(fptr);
return0;
}
This program takes a number from the user and stores in the file program.txt.
10
After you compile and run this program, you can see a text file program.txt created in C drive
of your computer. When you open the file, you can see the integer you entered.
fgetc( FILE * fp );
• fgets()
-fgets function is used to read a file line by line
Syntax
fgets (buffer, size, fp);
where
buffer – buffer to put the data in.
fp – file pointer
fscanf()
fscanf(FILE *fp, const char *format, ...)
This function is used to read strings from a file, but it stops reading after encountering the
first space character or newline.
#include <stdio.h>
main() {
FILE *fp;
char buff[255];
fp = fopen("/tmp/test.txt", "r");
fscanf(fp, "%s", buff);
printf("1 : %s\n", buff );
}
When the above code is compiled and executed, it reads the file created in the previous
section and produces the following result −
1 : This
2: is testing for fprintf...
#include <stdio.h>
intmain() {
FILE * file_pointer;
char buffer[30], c;
Result:
----read a line----
Learning FILEin C
12
1. In the above program, we have opened the file called "fprintf_test.txt" which was
previously written using fprintf() function, and it contains "Learning FILE in C"
string. We read it using the fgets() function which reads line by line where the buffer
size must be enough to handle the entire line.
2. We reopen the file to reset the pointer file to point at the beginning of the file. Create
various strings variables to handle each word separately. Print the variables to see
their contents. The fscanf() is mainly used to extract and parse data from a file.
3. Reopen the file to reset the pointer file to point at the beginning of the file. Read data
and print it from the file character by character using getc() function until the EOF
statement is encountered
4. After performing a reading operation file using different variants, we again closed the
file using the fclose function.
#include<stdio.h>
#include<stdlib.h>
intmain()
{
intnum;
FILE *fptr;
fscanf(fptr,"%d", &num);
return0;
This program reads the integer present in the program.txt file and prints it onto the screen. If
you successfully created the file from above example , running this program will get you the
integer you entered.
13
All of these functions read a character from input and return an integer value. The integer is
returned to accommodate a special value used to indicate failure. The value EOF is generally
used for this purpose.
1) getc():
It reads a single character from a given input stream and returns the corresponding
integer value (typically ASCII value of read character) on success. It returns EOF on
failure.
Syntax:
getc(FILE *stream);
Example for getc()
#include <stdio.h>
int main()
{
printf("%c", getc(stdin));
return(0);
}
Input: g (press enter key)
Output: g
An Example Application : C program to compare two files and report mismatches.
2) getchar():
The difference between getc() and getchar() is getc() can read from any input stream,
but getchar() reads from standard input. So getchar() is equivalent to getc(stdin).
Syntax:
int getchar(void);
Example:
// Example for getchar() in C
#include <stdio.h>
int main()
{
printf("%c", getchar());
return 0;
}
Input: g(press enter key)
Output: g
3) getch():
getch() is a nonstandard function and is present in conio.h header file which is mostly
used by MS-DOS compilers like Turbo C.
-Like above functions, it reads also a single character from keyboard. But it does not
use any buffer, so the entered character is immediately returned without waiting for
the enter key.
14
Syntax:
getch();
Example:
// Example for getch() in C
#include <stdio.h>
#include <conio.h>
int main()
{
printf("%c", getch());
return 0;
}
Input: g (Without enter key)
Output: Program terminates immediately.
But when you use DOS shell in Turbo C,
it shows a single g, i.e., 'g'
4) getche()
-Like getch(), this is also a non-standard function present in conio.h. It reads a single
character from the keyboard and displays immediately on output screen without waiting for
enter key.
Syntax:
getche(void);
Example:
#include <stdio.h>
#include <conio.h>
// Example for getche() in C
intmain()
{
printf("%c", getche());
return 0;
}
Input: g(without enter key as it is not buffered)
Output: Program terminates immediately.
But when you use DOS shell in Turbo C,
double g, i.e., 'gg'
#include<stdio.h>
intmain()
FILE *fp;
char ch;
fp=fopen("one.txt","w");
printf("Enter data...");
while((ch=getchar())!= EOF){
putc(ch,fp);
fclose(fp);
fp=fopen("one.txt","r");
while((ch=getc(fp)!= EOF)
printf("%c",ch);
fclose(fp);
return0;
These are the simplest file operations. Getc() stands for get character, and putc() stands for
put character. These two functions are used to handle only a single character at a time.
#include <stdio.h>
int main() {
FILE * fp;
char c;
printf("File Handling\n");
//open a file
fp = fopen("demo.txt", "w");
//writing operation
while ((c = getchar()) != EOF) {
putc(c, fp);
16
}
//close file
fclose(fp);
printf("Data Entered:\n");
//reading
fp = fopen("demo.txt", "r");
while ((c = getc(fp)) != EOF) {
printf("%c", c);
}
fclose(fp);
return 0;
}
Output:
File Handling
Hello VSSUT
Data Entered:
Hello VSSUT
1. In the above program we have created and opened a file called demo in a write mode.
2. After a write operation is performed, then the file is closed using the fclose function.
3. We have again opened a file which now contains data in a reading mode. A while
loop will execute until the eof is found. Once the end of file is found the operation
will be terminated and data will be displayed using printf function.
4. After performing a reading operation file is again closed using the fclose function.
#include<stdio.h>
struct emp
char name[10];
int age;
};
void main()
struct emp e;
17
FILE *p,*q;
p =fopen("one.txt","a");
q =fopen("one.txt","r");
fclose(p);
do
while(!feof(q));
In this program, we have created two FILE pointers and both are refering to the same file but
in different modes.
fprintf() function directly writes into the file, while fscanf() reads from the file, which can
then be printed on the console using standard printf() function.
To write into a binary file, you need to use the fwrite() function. The functions take four
arguments:
address of data to be written in the disk
size of data to be written in the disk
number of such type of data
pointer to the file where you want to write.
fwrite(addressData, sizeData, numbersData, pointerToFile);
#include<stdio.h>
#include<stdlib.h>
Struct threeNum
};
int main()
int n;
FILE *fptr;
exit(1);
num.n1 = n;
num.n2 = 5*n;
num.n3 = 5*n + 1;
fclose(fptr);
return0;
#include<stdio.h>
20
#include<stdlib.h>
struct threeNum
{
int n1, n2, n3;
};
int main()
{
int n;
struct threeNum num;
FILE *fptr;
return0;
}
In this program, you read the same file program.bin and loop through the records one by one.
In simple terms, you read one threeNum record of threeNum size from the file pointed
by *fptr into the structure num.
You'll get the same records you inserted in Example 2.
Sntax of fseek()
The first parameter stream is the pointer to the file. The second parameter is the position of
the record to be found, and the third parameter specifies the location where the offset starts.
Example :fseek()
#include <stdio.h>
int main()
{
FILE *fp;
fp = fopen("test.txt", "r");
return 0;
}
Output:
81
1. C program to read name and marks of n number of students and store them in a file.
#include <stdio.h>
int main()
{
char name[50];
int marks, i, num;
FILE *fptr;
fptr = (fopen("C:\\student.txt", "w"));
if(fptr == NULL)
{
printf("Error!");
exit(1);
}
scanf("%s", name);
fclose(fptr);
return 0;
}
2. C program to read name and marks of n number of students from and store them in
a file. If the file previously exits, add the information to the file.
#include <stdio.h>
int main()
{
char name[50];
int marks, i, num;
FILE *fptr;
fptr = (fopen("C:\\student.txt", "a"));
if(fptr == NULL)
{
printf("Error!");
exit(1);
}
fclose(fptr);
return 0;
}
23
#include<stdio.h>
#include<dirent.h>
int main(void)
DIR *d;
structdirent *dir;
d = opendir(".");
if (d)
printf("%s\n", dir->d_name);
closedir(d);
return(0);
File1.txt
File2.txt
File3.txt
File4.txt
File5.txt
File6.txt
File7.txt
dirent.h header file contains variables and functions related to directory streams.
24
We can also take the directory name as input from the user, and can also create a simple C
program to search for a particular file in a directory.
#include<stdio.h>
intmain()
char c[1000];
FILE *fptr;
exit(1);
fscanf(fptr,"%[^\n]", c);
fclose(fptr);
return 0;
#include<stdio.h>
#include<conio.h>
void main()
{ FILE *fp;
char ch;
int size = 0;
fp = fopen("MyFile.txt", "r");
if (fp == NULL)
else
printf("\nFile opened...");
fclose(fp);
#include<stdio.h>
26
#include<conio.h>
void main()
FILE *fptr;
char name[20];
int age;
float salary;
if (fptr == NULL)
return;
scanf("%s", name);
scanf("%d", &age);
scanf("%f", &salary);
fclose(fptr);
27
You can add any information in the file, like we have added Name, Age and Salary for some
employees, you can change the program as per your requirements.
You can even initialise a for loop, to add details of multiple employees to the file. All you
have to do is, ask user for number of employees for which data has to be stored, run
the for loop that many times and keep on adding the data to the file.
#include<stdio.h>
#include<errno.h>
void main()
int i;
long cnt;
cnt = count_characters(fp1);/* Make the pointer fp1 to point at the last character of the file
*/
while (cnt)
ch = fgetc(fp1);
28
fputc(ch, fp2);
cnt--;
else
perror("Error occured\n");
fclose(fp1);
fclose(fp2);
last_pos++;
return last_pos;
#include<stdio.h>
#include<stdio.h>
void main()
{
29
/* File_1.txt is the file with content and, File_2.txt is the file in which content of File_1 will
be copied */
char ch;
intpos;
return;
else
pos = ftell(fp1);
while (pos--)
fputc(ch, fp2);
fcloseall();
Here argc counts the number of arguments on the command line and argv[ ] is a pointer array
which holds pointers of type char which points to the arguments passed to the program.
Example:
#include <stdio.h>
#include <conio.h>
- argv[0] holds the name of the program and argv[1] points to the first command line
argument and argv[n] gives the last argument. If no argument is supplied, argc will be 1.
QUESTIONS: