CH 2 File Handling
CH 2 File Handling
A file is collection of data stored on secondary storage device link hard disk.
• File is created for permanent storage of data. It is readymade structure.
• A file is basically used because real-life application involve large amounts of data and
in such applications the console-oriented I/O operation cause two major problems:
1) It become bulky and time consuming to handle huge amount of data through
terminals.
2) Second, when doing I/o using terminal, the entire data is lost when either the
program is terminated or computer is turned off.
File Opening Mode:-
File can be opened in basic Three mode-
• Read Mode
• Writing Mode
• Appending Mode
Types of Files in C
A file can be classified into two types based on the way the file stores the data. They
are as follows:
Text Files
Binary Files
• 1. Text Files
s of File:-
• 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.
File Management:- When working on file we need to declare pointer of
type file.
FILE *fptr;
#include <stdio.h>
// Open the file in binary read mode
int main() {
file = fopen("temp.dat", "rb");
int array[] = {10, 20, 30, 40, 50};
FILE *file; if (file == NULL) {
int i; printf("Could not open file");
// Open a temporary file in binary write mode return 1;
file = fopen("temp.dat", "wb"); }
if (file == NULL) { // Display the elements of the array read from the file
printf("Could not open file"); for (i = 0; i < 5; i++) {
return 1; printf("%d\n", getw(file));
} }
// Write the elements of the array to the file // Close the file
for (i = 0; i < 5; i++) { fclose(file);
putw(array[i], file);
} return 0;
// Close the file }
fclose(file);
Character oriented Functions-
fputc(),fgetc()
• fputc() is used to write characters to the file
Syntax: Fputc(c,fp);
Where C is a character.
Fp is file pointer.
Parameters
File_pointer: It is the pointer that points to the FILE for which we want to check the error.
Return Value
It returns a non-zero value if an error occurred, otherwise, it returns 0.
2) feof()
The feof() function is used to check whether end-of-file indicator is set for a file steam.
Syntax
stream: It is the pointer that points to the FILE for which we want to check the error.
Return Value