0% found this document useful (0 votes)
24 views

LectureMaterial 3

Uploaded by

devaki meena
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views

LectureMaterial 3

Uploaded by

devaki meena
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

File Handling in C

File handing in C is the process in which we create, open, read, write, and close
operations on a file.
o Creation of the new file
o Opening an existing file
o Reading from the file
o Writing to the file
o Closing the file

File Functions:
C language provides different functions such as fopen(), fwrite(), fread(), fseek(),
fprintf(), etc. to perform input, output, and many different C file operations in our
program.

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


Features of using files:
● Reusability: The data stored in the file can be accessed, updated, and deleted
anywhere and anytime providing high reusability.

● Portability: Without losing any data, files can be transferred to another in the
computer system. The risk of flawed coding is minimized with this feature.

● Efficient: A large amount of input may be required for some programs. File
handling allows you to easily access a part of a file using few instructions which
saves a lot of time and reduces the chance of errors.

● Storage Capacity: Files allow you to store a large amount of data without having to
worry about storing everything simultaneously in a program.

Types of Files in C
1. Text Files
2. Binary Files

1. Text Files
A text file contains data in the form of ASCII characters and is generally used to store
a stream of characters.
● Each line in a text file ends with a new line character (‘\n’).
● It can be read or written by any text editor.
● They are generally stored with .txt file extension.
● Text files can also be used to store the source code.

2. Binary Files
A binary file contains data in binary form (i.e. 0’s and 1’s) instead of ASCII
characters. They contain data that is stored in a similar manner to how it is stored in the
main memory.
● The binary files can be created only from within a program and their contents can
only be read by a program.
● More secure as they are not easily readable.
● They are generally stored with .bin file extension.

C-File Operations
C file operations refer to the different possible operations that we can
perform on a file in C such as:
1. Creating a new file – fopen() with attributes as “a” or “a+” or “w” or
“w+”
2. Opening an existing file – fopen()
3. Reading from file – fscanf() or fgets()
4. Writing to a file – fprintf() or fputs()
5. Moving to a specific location in a file – fseek(), rewind()
6. Closing a file – fclose()

We can use one of the following modes in the fopen() function.

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

File Pointer in C
A file pointer is a reference to a particular position in the opened file. It is used in file
handling to perform all file operations such as read, write, close, etc. We use the FILE macro
to declare the file pointer variable. The FILE macro is defined inside <stdio.h> header file.

Syntax of File Pointer


FILE* pointer_name;

File Pointer is used in almost all the file operations in C.

Example of Opening a File


// C Program to create a file
#include <stdio.h>
#include <stdlib.h>
int main()
{
// file pointer
FILE* fptr;

// creating file using fopen() access mode "w"


fptr = fopen("file.txt", "w");

// checking if the file is created


if (fptr == NULL) {
printf("The file is not opened. The program will exit now");
exit(0);
}
else {
printf("The file is created Successfully.");
}

return 0;
}

Output
The file is created Successfully.

Reading From a File


The file read operation in C can be performed using functions fscanf() or fgets().
Both the functions performed the same operations as that of scanf and gets but with an
additional parameter, the file pointer. There are also other functions we can use to read
from a file. Such functions are listed below:

Function Description

Use formatted string and variable arguments list to take input from a
fscanf()
file.

fgets() Input the whole line from the file.

fgetc() Reads a single character from the file.

fgetw() Reads a number from a file.

fread() Reads the specified bytes of data from a binary file.

So, it depends on you if you want to read the file line by line or character by character.

Example:
FILE * fptr;
fptr = fopen(“fileName.txt”, “r”);
fscanf(fptr, "%s %s %s %d", str1, str2, str3, &year);
char c = fgetc(fptr);

Write to a File
The file write operations can be performed by the functions fprintf() and fputs() with
similarities to read operations. C programming also provides some other functions that
can be used to write data to a file such as:
Function Description

Similar to printf(), this function use formatted string and varible


fprintf()
arguments list to print output to the file.

fputs() Prints the whole line in the file and a newline at the end.
Function Description

fputc() Prints a single character into the file.

fputw() Prints a number to the file.

fwrite() This functions write the specified amount of bytes to the binary file.

Example:

FILE *fptr ;
fptr = fopen(“fileName.txt”, “w”);
fprintf(fptr, "%s %s %s %d", "We", "are", "in", 2012);
fputc("a", fptr);

Closing a File
The fclose() function is used to close the file. After successful file operations, you must always
close a file to remove it from the memory.

Syntax of fclose()
fclose(file_pointer);

where the file_pointer is the pointer to the opened file.

Example:
FILE *fptr ;
fptr= fopen(“fileName.txt”, “w”);
---------- Some file Operations -------
fclose(fptr);

Example : Program to Create a File, Write in it, and Close the File

#include <stdio.h>
#include <string.h>
int main()
{
FILE* filePointer;
char dataToBeWritten[50] = "GeeksforGeeks-A Computer "
"Science Portal for Geeks";

// Open the existing file GfgTest.c using fopen()


// in write mode using "w" attribute
filePointer = fopen("GfgTest.txt", "w");

// Check if this filePointer is null


// which maybe if the file does not exist
if (filePointer == NULL) {
printf("GfgTest.txt file failed to open.");
}
else {

printf("The file is now opened.\n");

// Write the dataToBeWritten into the file


if (strlen(dataToBeWritten) > 0) {

// writing in the file using fputs()


fputs(dataToBeWritten, filePointer);
fputs("\n", filePointer);
}

// Closing the file using fclose()


fclose(filePointer);

printf("Data successfully written in file "


"GfgTest.txt\n");
printf("The file is now closed.");
}

return 0;
}

Output:

The file is now opened.


Data successfully written in file GfgTest.txt
The file is now closed.

Example: Program to Open a File, Read from it, And Close the
File

// C program to Open a File,


// Read from it, And Close the File
#include <stdio.h>
#include <string.h>

int main()
{

// Declare the file pointer


FILE* filePointer;

// Declare the variable for the data to be read from file

char dataToBeRead[50];

// Open the existing file GfgTest.txt using fopen()


// in read mode using "r" attribute
filePointer = fopen("GfgTest.txt", "r");

// Check if this filePointer is null


// which maybe if the file does not exist

if (filePointer == NULL) {
printf("GfgTest.txt file failed to open.");
}
else {

printf("The file is now opened.\n");

// Read the dataToBeRead from the file


// using fgets() method

while (fgets(dataToBeRead, 50, filePointer) != NULL)


{

// Print the dataToBeRead


printf("%s", dataToBeRead);
}

// Closing the file using fclose()


fclose(filePointer);

printf(
"Data successfully read from file GfgTest.txt\n");
printf("The file is now closed.");
}
return 0;
}

Output:
The file is now opened.
GeeksforGeeks-A Computer Science Portal for Geeks
Data successfully read from file GfgTest.txt
The file is now closed.

Random Access Files


In C language, a random access file allows us to read or write any data in our disc
file without reading or writing every piece of data before it. We can quickly
search for data, edit it, or even delete it in a random-access file.

Random accessing of files in C language can be done with the help of the
following functions −
ftell ( )
rewind ( )
fseek ( )

ftell ( )
It returns the current position of the file ptr.

Note − ftell ( ) is used for counting the number of characters which are entered into a
file.

rewind ( )
It makes file ptr move to beginning of the file.

The syntax is as follows −


rewind (file pointer);

For example,
FILE *fp;
-----
-----
rewind (fp);
n = ftell (fp);
printf ("%d”, n);

Output
The output is as follows −
0 (always).

fseek ( )
It is to make the file pntr point to a particular location in a file.

The syntax is as follows −

fseek(file pointer, offset, position);


Offset
● The no of positions to be moved while reading or writing.
● If can be either negative (or) positive.
o Positive - forward direction.
o Negative – backward direction.

Position
It can have three values, which are as follows −

● 0 – Beginning of the file.


● 1 – Current position.
● 2 – End of the file.
Example
● fseek (fp,0,2) - fp moved 0 bytes forward from the end of the file.
● fseek (fp, 0, 0) – fp moved 0 bytes forward from beginning of the file
● fseek (fp, m, 0) – fp moved m bytes forward from the beginning of the file.
● fseek (fp, -m, 2) – fp moved m bytes backward from the end of the file.

You might also like