File in C: - A file in C is a collection of data stored
permanently on a storage device (hard disk).
OR
A file is
used to store data permanently so that it can be used later, even after the
program ends.
Advantages and Disadvantages of File in C
Advantages of
File in C
- Data is stored permanently
- Data can be used again after
program ends
- Can store large amount of
data
- Easy to read and write data
- Useful for records and
databases
- Binary files provide fast
processing
Disadvantages
of File in C
- File handling is slower than
memory access
- Binary files are not human readable
- File operations are more
complex than variables
- Data may be lost if file is not
closed properly
- Error handling is required
Types of Files in C
Files in C
can be classified in two ways:
(A) Based on
Storage Format
Text File:- A text files stores data in human-readable
form. The data is saved as characters, so it can be easily opened and read
using applications like Notepad. Text files are easy to understand and are
commonly used to store simple data such as names, marks, or messages. However,
they require more storage space and are slower than binary files.
2 Binary File:- A binary file stores data in binary format (0
and 1). It is not readable by humans and cannot be opened in Notepad. Binary
files are faster and take less storage space compared to text files. They are
mainly used to store large amounts of data such as records, structures, and
images.
(B) Based on Access Method
3 Sequential File:- A sequential file stores data
in sequence, and the data is accessed one record after another. To read any
data, we must start reading from the beginning of the file. Text files usually
follow sequential access. This method is simple but time-consuming for large
files.
4 Random File:- A random file allows direct access to data from any location in the file. Using functions like fseek(), we can move the file pointer to a specific position and read or write data directly. This method is fast and efficient and is mainly used in binary files for record-based systems.
File Pointer:-
A file
pointer is a special pointer used to handle files in C. It is used to connect
program to the file. It is used in all file operations
Declaration:
FILE *fp;
Opening a File
Opening a file means creating a connection
between the program and the file stored on the disk. In C, the fopen() function is used to open a file.
It requires two arguments: the name of the file and the mode in which the file
is to be opened. The mode decides whether the file will be opened for reading,
writing, appending, or in binary form. If the file is opened successfully, fopen() returns a file pointer;
otherwise, it returns NULL.
Therefore, it is always important to check whether the file has been opened
successfully before performing any operation on it.
fopen() Function :- The fopen() function
is used to open a file in C. It creates a connection between the program and
the file. If the file opens successfully, it returns a file pointer; otherwise,
it returns NULL.
Syntax:
fp = fopen("filename",
"mode");
File Opening Modes
Text File Modes
|
Mode |
Meaning |
|
r |
Open text
file for reading |
|
w |
Open text
file for writing (old data erased) |
|
a |
Open text
file for appending data |
|
r+ |
Read and
write text file |
|
w+ |
Write and
read text file |
|
a+ |
Append and
read text file |
Binary File Modes
|
Mode |
Meaning |
|
rb |
Open
binary file for reading |
|
wb |
Open
binary file for writing |
|
ab |
Open
binary file for appending |
|
rb+ |
Read and
write binary file |
|
wb+ |
Write and
read binary file |
|
ab+ |
Append and
read binary file |
5Closing a File
Function Used: The fclose() function is used to close
an open file in C. It saves all data properly and releases the memory used by
the file.
fclose(fp);
Text File Input Functions
1 fprintf():- fprintf() is used to
write formatted data to a text file. It works like printf() but writes output into a file instead of the screen.
It is useful for writing numbers, characters, and strings in a formatted way.
Syntax:
fprintf(fp, "format string", variables);
2 fputc():- fputc() is used to
write a single character to a text file. It writes one character at a time at
the current file position and is useful for character-by-character file
writing.
Syntax:
fputc(character, fp);
3 fputs():- fputs() is used to
write a string to a text file. It writes the complete string to the file but
does not automatically add a new line at the end.
Syntax:
fputs(string, fp);
Text File Input Functions
1-fscanf():- fscanf() is used to
read formatted data from a text file. It works like scanf() but reads input from a file instead of the keyboard.
It is used to read numbers, characters, and strings in a formatted form.
Syntax:
fscanf(fp, "format string", &variables);
Syntax:
fgetc(fp);
3 fgets():- fgets() is used to
read a string from a text file. It reads characters from the file until a
newline is found or the given limit is reached. It is mainly used to read one
line at a time.
Syntax:
fgets(string, size, fp);
Simple C program using fprintf() and fscanf().
#include <stdio.h>
int main() {
FILE *fp;
int a = 50, b = 75, x, y;
char name[20] = "Ashok";
char str[20];
fp = fopen("data.txt", "w");
fprintf(fp, "%d %d\n", a, b);
fprintf(fp, "%s\n", name);
fclose(fp);
fp = fopen("data.txt", "r");
fscanf(fp, "%d %d", &x, &y);
fscanf(fp, "%s", str);
printf("%d %d\n", x, y);
printf("%s\n", str);
fclose(fp);
return 0;
}
Writing to Binary File
fwrite():- fwrite() is used to
write data to a binary file. It stores data in binary form, which is faster and
uses less space. It is commonly used to write numbers, arrays, and structures
into a file.
Syntax:
fwrite(address, size, count, fp);
Reading from Binary File
fread():- fread() is used to read data from a binary file. It reads
data in the same order in which it was written. It is used to retrieve binary
data such as integers, floats, arrays, and structures.
Syntax:
fread(address, size, count, fp);
Simple C program using fwrite() and fread().
#include <stdio.h>int main() { FILE *fp; int a = 100; float b = 23.5; char ch = 'X'; int x; float y; char z; fp = fopen("data.bin", "wb"); fwrite(&a, sizeof(a), 1, fp); fwrite(&b, sizeof(b), 1, fp); fwrite(&ch, sizeof(ch), 1, fp); fclose(fp); fp = fopen("data.bin", "rb"); fread(&x, sizeof(x), 1, fp); fread(&y, sizeof(y), 1, fp); fread(&z, sizeof(z), 1, fp); printf("%d\n%.2f\n%c\n", x, y, z); fclose(fp); return 0;}
Difference Between Text File and Binary File
|
Text File |
Binary File |
|
Stores
data in readable (character) form |
Stores
data in binary (0 and 1) form |
|
Can be
opened and read using Notepad |
Cannot be
read using
Notepad |
|
Uses
functions like fprintf() and fscanf() |
Uses
functions like fwrite() and fread() |
|
Requires more
storage space |
Requires less
storage space |
|
Slower compared to binary files |
Faster for reading and writing |
Random Access in Files (Paragraph)
Random
access in C allows us to read or write data at any position in a file without
reading it sequentially from the beginning. It is mostly used with binary
files. Functions like fseek(), ftell(), and rewind() help move the file pointer to a
specific location, find the current position of the pointer, or return it to
the start of the file, making file operations faster and efficient.
1fseek():-Moves the file pointer to a specific
position in a file.
Syntax:
fseek(fp, offset, origin);
C program using fseek() to access a specific record in a binary file.
#include
<stdio.h>
#include <stdlib.h>
int main() {
FILE *fp;
int numbers[5] = {10, 20, 30, 40, 50};
int num;
fp = fopen("data.bin",
"wb");
fwrite(numbers, sizeof(int), 5, fp);
fclose(fp);
fp = fopen("data.bin",
"rb");
fseek(fp, 2 * sizeof(int), SEEK_SET);
fread(&num, sizeof(int), 1, fp);
printf("%d\n", num);
fclose(fp);
return 0;
}
2 ftell():- Returns the current position of the
file pointer in a file.
Syntax:
ftell(fp);
3rewind():- Moves the file pointer back to the
beginning of the file.
Syntax:
rewind(fp);
No comments:
Post a Comment