File Handling
with various statements/syntaxes in Programming and their output in C Language.
by
Md Farrukh Asif
C File Handling
·
A file is a
container in computer storage devices used for storing data.
Why files are needed?
Storing
your data in a file is a great way to ensure that it won't be lost if the
program terminates unexpectedly. This can save you a lot of time, especially
when dealing with a large amount of data. Additionally, having your data in a
file allows for easy access and transfer between computers without any
modifications.
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, known as .txt files, can be effortlessly
created using simple text editors like Notepad. Upon opening these files, you
will see the contents displayed as plain text, making it easy to edit or delete
them as needed. Text files are low-maintenance, easily readable, and offer
minimal security while requiring a larger storage space. space.
2. Binary files
Binary files, often denoted with the .bin
extension, are a common file type on your computer. Unlike plain text files,
they store data in a binary format comprised of 0's and 1's. Due to their
nature, they can accommodate larger volumes of data, are not easily readable,
and offer enhanced security compared to text files..
C Language:
C for the
beginner 's by Md Farrukh Asif
Operators
in C by Md. Farrukh Asif
C's
Control Flow by Md. Farrukh Asif
String handling in C by Md Farrukh Asif
The
Function of C Language by Md. Farrukh Asif
File
Handling With Various Statements/Syntaxes In Programming And Their Output In C
Language.
C
For Beginner's Programming With Output. Course Code – 106 [‘C’]) TMBU,BGP
Bca
Solved Examination Questions With Answers Course Code – 106 [‘C’]) Tmbu,Bgp
File Operations
In C, you can perform four major operations on
files, either text or binary:
1.
Creating a new
file
2.
Opening an
existing file
3.
Closing a file
4.
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 a file - for
creation and edit
Opening a file can be accomplished by using the
fopen() function, which is defined in the stdio.h
header file. The syntax for
opening a file in standard I/O is as follows:
ptr
= fopen("fileopen","mode").
As an example,
fopen("E:\\cprogram\\newprogram.txt","w");
fopen("E:\\cprogram\\oldprogram.bin","rb");
Suppose the file newprogram.txt does not exist in
the location E:\cprogram. The first function is used to create a new file named
newprogram.txt and opens it for writing in the mode 'w', allowing the creation
and editing (overwriting) of the file contents.
Now, let's consider that the second binary file,
oldprogram.bin, exists in the location E:\cprogram. The second function is
intended to open the existing file for reading in binary mode 'rb'. This
reading mode limits the operation to reading the file, disallowing any writing
into the file.
Opening Modes in Standard I/O |
||
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. |
w |
Open for writing. |
If the file exists, its contents
are overwritten. |
wb |
Open for writing in binary mode. |
If the file exists, its contents
are overwritten. |
a |
Open for append. |
If the file does not exist, it
will be created. |
ab |
Open for append in binary mode. |
If the file does not exist, it
will be created. |
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. |
w+ |
Open for both reading and
writing. |
If the file exists, its contents
are overwritten. |
wb+ |
Open for both reading and
writing in binary mode. |
If the file exists, its contents
are overwritten. |
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. |
Closing a File
The file (both text and binary) should be closed
after reading\writing.
Closing a file is performed using
the fclose() function.
fclose(fptr);
Here, fptr is a file pointer associated
with the file to be closed.
Reading and writing to
a text file
When working with text files, we can utilize the
functions fprintf() and fscanf(). These are essentially the file counterparts
of printf() and scanf(). The key distinction is that fprintf() and fscanf()
require a pointer to the FILE structure.
Example 1: Write to a
text file
#include <stdio.h>
#include <stdlib.h>
int main()
{
int num;
FILE
*fptr;
// use
appropriate location if you are using MacOS or Linux
fptr =
fopen("C:\\program.txt","w");
if(fptr ==
NULL)
{
printf("Error!");
exit(1);
}
printf("Enter num: ");
scanf("%d",&num);
fprintf(fptr,"%d",num);
fclose(fptr);
return 0;
}
===========
This program takes a number from the user and
stores in the file program.txt.
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.
Example 2: Read from a
text file
#include <stdio.h>
#include <stdlib.h>
int main()
{
int num;
FILE
*fptr;
if ((fptr
= fopen("C:\\program.txt","r")) == NULL){
printf("Error! opening file");
//
Program exits if the file pointer returns NULL.
exit(1);
}
fscanf(fptr,"%d",
&num);
printf("Value of n=%d", num);
fclose(fptr);
return 0;
}
============
This code reads the integer stored in the
program.txt file and displays it on the screen. If you've followed the
instructions from Example 1 to create the file, running this code will output
the integer you inputted. Other functions like fgetchar() and fputc() can also
be applied in a similar manner.
In addition, when dealing with binary files, the
functions fread() and fwrite() are used for reading from and writing to a file
on the disk. These functions are specifically designed for binary files.
Writing to a binary
file
To write into a binary file, you need to use
the fwrite() function. The functions take four arguments:
1.
address of data
to be written in the disk
2.
size of data to
be written in the disk
3.
number of such
type of data
4.
pointer to the
file where you want to write.
fwrite(addressData, sizeData, numbersData,
pointerToFile);
Example 3:
Write to a binary file
using fwrite()
#include <stdio.h>
#include <stdlib.h>
struct threeNum
{
int n1,
n2, n3;
};
int main()
{
int n;
struct
threeNum num;
FILE
*fptr;
if ((fptr
= fopen("C:\\program.bin","wb")) == NULL){
printf("Error! opening file");
//
Program exits if the file pointer returns NULL.
exit(1);
}
for(n = 1;
n < 5; ++n)
{
num.n1
= n;
num.n2
= 5*n;
num.n3
= 5*n + 1;
fwrite(&num, sizeof(struct threeNum), 1, fptr);
}
fclose(fptr);
return 0;
}
==========
In this program, we create a new
file program.bin in the C drive.
In the main function, we define a structure called
threeNum, which consists of three numbers: n1, n2, and n3. Inside the for loop,
we use the fwrite() function to store the value into the file. The first
parameter of fwrite() takes the address of num, while the second parameter
takes the size of the threeNum structure. Since we're only inserting one
instance of num, the third parameter is 1. The last parameter, *fptr, points to
the file where we're storing the data. Finally, we close the file.
Reading from a binary
file
Function fread() also take 4 arguments
similar to the fwrite() function as above.
fread(addressData, sizeData, numbersData,
pointerToFile);
Example 4:
Read from a binary
file using fread()
#include <stdio.h>
#include <stdlib.h>
struct threeNum
{
int n1,
n2, n3;
};
int main()
{
int n;
struct
threeNum num;
FILE
*fptr;
if ((fptr
= fopen("C:\\program.bin","rb")) == NULL){
printf("Error! opening file");
//
Program exits if the file pointer returns NULL.
exit(1);
}
for(n = 1;
n < 5; ++n)
{
fread(&num, sizeof(struct threeNum), 1, fptr);
printf("n1: %d\tn2: %d\tn3: %d\n", num.n1, num.n2, num.n3);
}
fclose(fptr);
return 0;
}
========
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 3.
Getting data using
fseek()
When you have numerous records inside a file and
need to access a record at a specific position, you typically have to loop
through all the records before it to retrieve the desired record. This process
can consume a significant amount of memory and operation time. An alternative
that can make accessing the required data easier is using the fseek() function.
As its name implies, fseek() allows you to move the cursor to the specified
record in the file.
Syntax of fseek()
```Use a professional and informative tone```
The function `fseek` is used to set the file
position indicator for the stream represented by the pointer `stream`. The
`offset` parameter specifies the number of bytes to move the position
indicator, and the `whence` parameter specifies the reference position for the
offset.
Different whence in fseek() |
|
Whence |
Meaning |
SEEK_SET |
Starts the offset from the
beginning of the file. |
SEEK_END |
Starts the offset from the end
of the file. |
SEEK_CUR |
Starts the offset from the
current location of the cursor in the file. |
Example 5: fseek()
#include <stdio.h>
#include <stdlib.h>
struct threeNum
{
int n1,
n2, n3;
};
int main()
{
int n;
struct
threeNum num;
FILE
*fptr;
if ((fptr
= fopen("C:\\program.bin","rb")) == NULL){
printf("Error! opening file");
//
Program exits if the file pointer returns NULL.
exit(1);
}
// Moves
the cursor to the end of the file
fseek(fptr, -sizeof(struct threeNum), SEEK_END);
for(n = 1;
n < 5; ++n)
{
fread(&num, sizeof(struct threeNum), 1, fptr);
printf("n1: %d\tn2: %d\tn3: %d\n", num.n1, num.n2, num.n3);
fseek(fptr, -2*sizeof(struct threeNum), SEEK_CUR);
}
fclose(fptr);
return 0;
}
============
This program will start reading the records from
the file program.bin in the reverse order (last to first) and prints
it.
*** See You Again ***
************************
Share and Subscribe with Like
************************
No comments:
Post a Comment