You are on page 1of 48

File Handling in C

A file is a container in computer storage devices used for storing data.


Syllabus
Files - file handling

Defining & opening a file

Closing a file

Input/output operations on files

Error handling

Random access to files


Why files are needed?

When a program is terminated, the entire data is lost. Storing in a file will preserve
your data even if the program terminates.

If you have to enter a large number of data, it will take a lot of time to enter them
all.

However, if you have a file containing all the data, you can easily access the
contents of the file using a few commands in C.

You can easily move your data from one computer to another without any changes.
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

Text files are the normal .txt files. You can easily create text files using any simple text
editors such as Notepad.

When you open those files, you'll see all the contents within the file as plain text. You
can easily edit or delete the contents.

They take minimum effort to maintain, are easily readable, and provide the least
security and takes bigger storage space.
2. Binary files
Binary files are mostly the .bin files in your computer.

Instead of storing data in plain text, they store it in the binary form (0's and 1's).

They can hold a higher amount of data, are not readable easily, and provides
better security than text files.
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.

1. Creation of the new file

2. Opening an existing file

3. Reading from the file

4. Writing to the file

5. Deleting the file


Functions for file handling
No. Function Description
1 fopen() opens new or existing file
2 fprintf() write data into the file
3 fscanf() reads data from the file
4 fputc() writes a character into the file
5 fgetc() reads a character from file
6 fclose() closes the file
7 fseek() sets the file pointer to given position
8 fputw() writes an integer to file
9 fgetw() reads an integer from file
10 ftell() returns current position
11 rewind() sets the file pointer to the beginning of the file
Opening File: fopen()

We must open a file before it can be read, write, or update. The fopen() function is used
to open a file. The syntax of the fopen() is given below.

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

The fopen() function accepts two parameters:

1. The file name (string). If the file is stored at some specific location, then
we must mention the path at which the file is stored. For example, a file
name can be like "c://some_folder/some_file.ext".
2. The mode in which the file is to be opened. It is a string.
Mode Description
r opens a text file in read mode
w opens a text file in write mode
a opens a text file in append mode
r+ opens a text file in read and write mode
w+ opens a text file in read and write mode
a+ opens a text file in read and write mode
rb opens a binary file in read mode
wb opens a binary file in write mode
ab opens a binary file in append mode
rb+ opens a binary file in read and write mode
wb+ opens a binary file in read and write mode
ab+ opens a binary file in read and write mode
The fopen function works in the following way.

 Firstly, It searches the file to be opened.

 Then, it loads the file from the disk and place it into the buffer. The

buffer is used to provide efficiency for the read operations.

 It sets up a character pointer which points to the first character of the

file.
Closing the file
• It is considered as good practice, because it makes sure that:
• Changes are saved properly
• Other programs can use the file (if you want)
• Clean up unnecessary memory space
C Write To Files

• write something to the file we just created.

• The w mode means that the file is opened for writing.

• To insert content to it, you can use the fprintf() function and add the pointer

variable
#include <stdio.h>
int main() {
FILE *fptr;
// Open a file in writing mode
fptr = fopen("filename.txt", "w");

// Write some text to the file


Write operation
fprintf(fptr, "Some text");

// Close the file


fclose(fptr);

return 0;
}
Writing a File
Following is the simplest function to write individual characters to a stream −

int fputc( int c, FILE *fp );


The function fputc() writes the character value of the argument c to the output stream referenced by fp. It
returns the written character written on success otherwise EOF if there is an error.
You can use the following functions to write a null-terminated string to a stream −

int fputs( const char *s, FILE *fp );


The function fputs() writes the string s to the output stream referenced by fp. It returns a non-negative value
on success, otherwise EOF is returned in case of any error.
You can use

int fprintf(FILE *fp,const char *format, ...)


function as well to write a string into a file. Try the following example.
Append Content To a File

• If you want to add content to a file without deleting the old content, you can
use the a mode.

• The a mode appends content at the end of the file.


int main()
{
FILE *fptr;
// Open a file in append mode
fptr = fopen("filename.txt", "a");
// Append some text to the file
APPEND fprintf(fptr, "\nHi everybody!");
// Close the file
fclose(fptr);
return 0;
}
Reading a File
Given below is the simplest function to read a single character from a file −

int fgetc( FILE * fp );


The fgetc() function reads a character from the input file referenced by fp. The return value is the
character read, or in case of any error, it returns EOF. The following function allows to read a string
from a stream −

char *fgets( char *buf, int n, FILE *fp );


The functions fgets() reads up to n-1 characters from the input stream referenced by fp. It copies the
read string into the buffer buf, appending a null character to terminate the string.
If this function encounters a newline character '\n' or the end of the file EOF before they have read the
maximum number of characters, then it returns only the characters read up to that point including the

new line character. You can also use int fscanf(FILE *fp, const char *format, ...) function
to read strings from a file, but it stops reading after encountering the first space character.
Closing a File
To close a file, use the fclose( ) function. The prototype of this
function is −
int fclose( FILE *fp );
• The fclose(-) function returns zero on success, or EOF if there is an
error in closing the file.
• This function actually flushes any data still pending in the buffer
to the file, closes the file, and releases any memory used for the
file. The EOF is a constant defined in the header file stdio.h.
C program to read name and marks of n number
of students and store them in a file.
#include <stdio.h>
for(i = 0; i < num; ++i)
int main()
{
{
printf("For student%d\nEnter name: ", i+1);
char name[50];
scanf("%s", name);
int marks, i, num;
printf("Enter marks: ");
printf("Enter number of students: ");
scanf("%d", &marks);
scanf("%d", &num);
fprintf(fptr,"\nName: %s \nMarks=%d \n",
FILE *fptr;
name, marks);
fptr = (fopen("student.txt", "w"));
}
if(fptr == NULL)
{
fclose(fptr);
printf("Error!");
return 0;
exit(1);
}
}
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> #include <stdio.h>
#include<stdlib.h> #include<stdlib.h>
int main() int main()
{ {
char name[50]; char name[50];
int marks, i, num; int marks, i, num;

printf("Enter number of students: "); printf("Enter number of students: ");


scanf("%d", &num); scanf("%d", &num);

FILE *fptr; FILE *fptr;


fptr = (fopen("C:\\student.txt", "a")); fptr = (fopen("C:\\student.txt", "a"));
if(fptr == NULL) if(fptr == NULL)
{ {
printf("Error!"); printf("Error!");
exit(1); exit(1);
} }
C program to write all the members of an array of structures to a file
using fwrite(). Read the array from the file and display on the screen.
#include <stdio.h>
struct student
{
char name[50]; fwrite(stud1, sizeof(stud1), 1, fptr);
int height; fclose(fptr);
};
int main(){ fptr = fopen("file.txt", "rb");
struct student stud1[5], stud2[5]; fread(stud2, sizeof(stud2), 1, fptr);
FILE *fptr; for(i = 0; i < 5; ++i)
int i; {
printf("Name: %s\nHeight: %d",
fptr = fopen("file.txt","wb"); stud2[i].name, stud2[i].height);
for(i = 0; i < 5; ++i) }
{ fclose(fptr);
fflush(stdin); }
printf("Enter name: ");
gets(stud1[i].name);

printf("Enter height: ");


scanf("%d", &stud1[i].height);
}
Reading a File
Given below is the simplest function to read a single character from a file −
int fgetc( FILE * fp );
The fgetc() function reads a character from the input file referenced by fp. The return value is the character read, or in
case of any error, it returns EOF. The following function allows to read a string from a stream −
char *fgets( char *buf, int n, FILE *fp );
The functions fgets() reads up to n-1 characters from the input stream referenced by fp. It copies the read string into the
buffer buf, appending a null character to terminate the string.
If this function encounters a newline character '\n' or the end of the file EOF before they have read the maximum number
of characters, then it returns only the characters read up to that point including the new line character. You can also use
int fscanf(FILE *fp, const char *format, ...)
function to read strings from a file, but it stops reading after encountering the first space character.
#include <stdio.h> // Read and print the contents of the file
#include<stdlib.h> line by line
char line[100]; // Assuming a maximum line
int main() { length of 100 characters
// Declare a file pointer while (fgets(line, sizeof(line), file) !=
FILE *file; NULL)
{
// Open the file for reading printf("%s", line);
file = fopen("student.txt", "r"); }
// Check if the file opened successfully // Close the file
if (file == NULL) { fclose(file);
printf("Unable to open the file.\n");
exit(1); // Return an error code return 0; // Return success
} }
EOF, getc() and feof()

• In C, getc() returns the End of File (EOF) when the end of the file is reached.
• getc() also returns EOF when it fails.
• So, only comparing the value returned by getc() with EOF is not sufficient to
check for the actual end of the file.
• To solve this problem, C provides feof() which returns a non-zero value only if the
end of the file has reached, otherwise, it returns 0.
getc() Function in C

• The C getc() function is used to read a single character from the given file
stream. It is implemented as a macro in <stdio.h> header file.
• Syntax of getc()
int getc(FILE* stream);
• Parameters
stream: It is a pointer to a file stream to read the data from.
• Return Value
It returns the character read from the file stream.
If some error occurs or the End-Of-File is reached, it returns EOF.
feof() Function in C
The feof() function is used to check whether the file pointer to a stream is pointing to the end of the
file or not. It returns a non-zero value if the end is reached, otherwise, it returns 0.
Syntax of feof()
int feof(FILE* stream);

Parameters
It returns the character read from the file stream.
Return Value
If the end-of-file indicator has been set for the stream, the function returns a non-zero value (usually
1). Otherwise, it returns 0.
#include <stdio.h>
int main()
{
FILE* fp = fopen("Test1.txt", "r");
// Read the first character from the
file
getc() int ch = getc(fp);
while (ch != EOF) {
feof() putchar(ch);
ch = getc(fp);
}
EOF if (feof(fp))
printf("\n End of file reached.");
else
printf("\n Something went
wrong.");
fclose(fp);
return 0;
}
fgets() and gets() in C language

For reading a string value with spaces, we can use either gets() or fgets() in C
programming language.

fgets()
• The fgets() reads a line from the specified stream and stores it into the string pointed
to by str.

• It stops when either (n-1) characters are read, the newline character is read, or the
end-of-file is reached, whichever comes first.
Syntax
char *fgets (char *str, int n, FILE *stream);
Parameters
str: Pointer to an array of chars where the string read is copied.
n: Maximum number of characters to be copied into str (including the
terminating null character).
*stream: Pointer to a FILE object that identifies an input stream.

Note: stdin can be used as argument to read from the standard input.

Return Value
The fgets() function returns a pointer to the string where the input is stored.
Features of fgets()
•It follows some parameters such as Maximum length, buffer, and input device
reference.
•It is safe to use because it checks the array bound.
•It keeps on reading until a new line character is encountered or the maximum limit of
the character array.
#include <stdio.h>
#define MAX 15
int main()
{
// defining buffer Input:
Hello and welcome to Programming
char buf[MAX];
Output:
// using fgets to take input from stdin string is: Hello and welcome to Programming
fgets(buf, MAX, stdin);
printf("string is: %s\n", buf);
return 0;
}
gets()
• Reads characters from the standard input (stdin) and stores them as a C string into str until a
newline character or the end-of-file is reached.
• It is not safe to use because it does not check the array bound.
• It is used to read strings from the user until a newline character is not encountered.
Syntax

char *gets( char *str );


Parameters
• str: Pointer to a block of memory (array of char) where the string read is copied as a C string.
• Return Value
• The function returns a pointer to the string where input is stored
// C program to illustrate
// gets()
#include <stdio.h>
#define MAX 15

int main()
{
// defining buffer
char buf[MAX];

printf("Enter a string: ");

// using gets to take string from stdin


gets(buf);
printf("string is: %s\n", buf);

return 0;
}
fscanf Function in C
Tired of all the clumsy syntax to read from files? well, fscanf comes to the rescue. This function
is used to read the formatted input from the given stream in the C language.

Syntax:
int fscanf(FILE *ptr, const char *format, ...)
fscanf reads from a file pointed by the FILE pointer (ptr), instead of reading from the input
stream.

Return Value: It returns zero, if unsuccessful. Otherwise, it returns The input string, if
successful.
// C Program to demonstrate fscanf
#include <stdio.h>

// Driver Code
int main()
{
FILE* ptr = fopen("abc.txt", "r");
if (ptr == NULL) {
printf("no such file.");
return 0;
}
char buf[100];
while (fscanf(ptr, "%*s %*s %s ", buf) == 1)
printf("%s\n", buf);

return 0;
}
The %*s in scanf is used to ignore some input as required. In this case, it
ignores the input until the next space or newline. Similarly, if you write
%*d it will ignore integers until the next space or newline.
scanf() fscanf()

1. It is used to read standard input. This function is used to read input from a file

Its syntax is -: Its syntax is -:


2.
scanf(const char *format, …) fscanf(FILE *stream, const char *format, …)

It requires Format specifiers to take input of


3. It reads the stream in the form of byte
a particular type.

It takes three parameters that are -:


4. Whitespace character , Non-whitespace It is defined in header file #include <stdio.h>
character,Format specifiers
fread() Function

• The fread() is a standard library function used to read the given amount of data from a file
stream. Defined inside <stdio.h>, the fread() function reads the given number of elements of
specific size from the file stream and stores it in the buffer memory. The total number of bytes
read by fread() function is the number of elements read multiplied by the size of each element
in bytes.
• Syntax of C fread()
size_t fread(void * buffer, size_t size, size_t count, FILE * stream);
• The file position indicator is automatically moved forward by the number of bytes read. If the
objects being read are not trivially copy-able, such as structures or complex data types then it
does not behave properly.

You might also like