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

File Handling in C

File Handling in C language PPT

Uploaded by

A EDITS
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

File Handling in C

File Handling in C language PPT

Uploaded by

A EDITS
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 16

File Handling in

C Language
By Muhammad Ahmad (25)
BS SE

DEPARTMENT OF COMPUTING
101001101001000010101
0011110111011011011010
101000011100101011001

F
010100111010100010101

ile
Handlin
0001011010110110110100
010101110001010100010
1000101110101100010011
010011010010000101010

g
0111101110110110110101
010000111001010110010
101001110101000101010
0010110101101101101001
File handling is one of the most important parts of
programming. A file is a container in computer storage
devices used for storing data. File handling in C enables us to
create, update, read, and delete the files stored on the local
file system through our C program.

DATA
Why files are needed?
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:

Text files Binary files


Text files are the normal .txt files. You
can easily create text files using any Binary files are mostly the .bin files in
simple text editors such as Notepad. your computer. Instead of storing data
in plain text, they store it in the binary
form (0's and 1's).
File Operations
In C, you can perform four major operations on files, either text or binary:

Creating a new file Closing a file

Opening an existing file Reading from and writing


information to a file

Working with files


When working with files, you need to declare a pointer of type file. This declaration is needed for communication between the file
and the program.

FILE *fptr;
Opening Modes in Standard I/O
The syntax for opening a file in standard I/O is:
ptr = fopen("fileopen","mode");
Mode Meaning of Mode During Inexistence of file
• r Open for reading. If the file does not exist, fopen() returns NULL.

• rb Open for reading in binary mode. If the file does not exist, fopen() returns NULL.

If the file exists, its contents are overwritten.


• w Open for writing.
If the file does not exist, it will be created.

If the file exists, its contents are overwritten.


• wb Open for writing in binary mode.
If the file does not exist, it will be created.

Open for append.


• a If the file does not exist, it will be created.
Data is added to the end of the file.
Open for append in binary mode.
• ab If the file does not exist, it will be created.
Data is added to the end of the file.
• r+ Open for both reading and writing. If the file does not exist, fopen() returns NULL.

• rb+ Open for both reading and writing in binary mode. If the file does not exist, fopen() returns NULL.

If the file exists, its contents are overwritten.


• w+ Open for both reading and writing.
If the file does not exist, it will be created.

If the file exists, its contents are overwritten.


• wb+ Open for both reading and writing in binary mode.
If the file does not exist, it will be created.

• a+ Open for both reading and appending. If the file does not exist, it will be created.

• ab+ Open for both reading and appending in binary mode. If the file does not exist, it will be created.
Create a File
To create a file, you can use the w mode inside the fopen() function.

The w mode is used to write to a file. However, if the file does not exist, it will create one for you:

Example
FILE *fptr;
// Create a file
fptr = fopen("filename.txt", "w");
// Close the file
fclose(fptr);

Note: The file is created in the same directory as your other C files, if nothing else is specified.

On our computer, it looks like this:

Tip: If you want to create the file in a specific


folder, just provide an absolute path:

fptr = fopen("C:\directoryname\filename.txt", "w");


Closing the file
fclose() function

This will close the file when we are done with it.
FILE *fptr;
It is considered as good practice, because it makes sure that: // Create a file
fptr = fopen("filename.txt", "w");
• Changes are saved properly // Close the file
• Other programs can use the file (if you want) fclose(fptr);
• Clean up unnecessary memory space
Write To a File
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 (fptr in our example) and some text:

Example
FILE *fptr;

// Open a file in writing mode


fptr = fopen("filename.txt", "w");
// Write some text to the file
fprintf(fptr, "Some text");
// Close the file
fclose(fptr);

As a result, when we open the file on our computer, it looks like this:
Note: If you write to a file that already exists, the old content is deleted, and the new content is inserted. This is important to know, as you
might accidentally erase existing content.

For example:
fprintf(fptr, "Hello World!");
As a result, when we open the file on our computer, it says "Hello World!" instead of "Some text":

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: As a result, when we open the file on our computer, it looks like this:

Example
FILE *fptr;

// Open a file in append mode


fptr = fopen("filename.txt", "a");

// Append some text to the file


fprintf(fptr, "\nHi everybody!");

// Close the file


fclose(fptr); Note: Just like with the w mode; if the file does not exist, the a mode will create a new file with the "appended" content.
Read a File
To read from a file, you can use the r mode:

Example
FILE *fptr;

// Open a file in read mode


fptr = fopen("filename.txt", "r");

This will make the filename.txt opened for reading.


Next, we need to create a string that should be big enough to store the content of the file.
For example, let's create a string that can store up to 100 characters:

Example
FILE *fptr;

// Open a file in read mode


fptr = fopen("filename.txt", "r");

// Store the content of the file


char myString[100];

In order to read the content of filename.txt, we can use the fgets() function.
The fgets() function takes three parameters:

Example
fgets(myString, 100, fptr);
1.The first parameter specifies where to store the file content, which will be in the myString array we just created.
2.The second parameter specifies the maximum size of data to read, which should match the size of myString (100).
3.The third parameter requires a file pointer that is used to read the file (fptr in our example).

Now, we can print the string, which will output the content of the file:

Example
FILE *fptr;

// Open a file in read mode


fptr = fopen("filename.txt", "r");

// Store the content of the file


char myString[100];

// Read the content and store it inside myString


fgets(myString, 100, fptr);

// Print the file content Note: The fgets function only reads the first line of the file. If
printf("%s", myString); you remember, there were two lines of text in filename.txt.
// Close the file
fclose(fptr);

Hello World!
To read every line of the file, you can use a while loop:

Example
FILE *fptr;

// Open a file in read mode


fptr = fopen("filename.txt", "r");

// Store the content of the file


char myString[100];

// Read the content and print it


while(fgets(myString, 100, fptr)) { Good Practice
printf("%s", myString); If you try to open a file for reading that does not exist, the fopen() function will return NULL.
Tip: As a good practice, we can use an if statement to test for NULL, and print some text instead (when the file
} does not exist):

// Close the file Example


FILE *fptr;
fclose(fptr); // Open a file in read mode
fptr = fopen("loremipsum.txt", "r");
Output: // Print some text if the file does not exist
if(fptr == NULL) {
Hello World! printf("Not able to open the file.");
Hi everybody! }
// Close the file
fclose(fptr);
We can create a more sustainable code if we use our "read a file" example above again:

Example
If the file exist, read the content and print it. If the file does not exist, print a message:
FILE *fptr;

// Open a file in read mode


fptr = fopen("filename.txt", "r");

// Store the content of the file


char myString[100];

// If the file exist


if(fptr != NULL) {

// Read the content and print it


OUTPUT:
while(fgets(myString, 100, fptr)) {
printf("%s", myString);
}

// If the file does not exist


} else {
printf("Not able to open the file.");
}

// Close the file


fclose(fptr);

You might also like