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;
• Basic file operations are:-
• 1) Opening a file 2) Closing a file 3) Reading data from file
4) Writing in a file
1) Opening a file- This operation is performed using fopen() functions
defined in the stdio.h header file. Fopen() is used to create new file
or open existing file.
Syntax: fptr =fopen(“filename”,”mode”);
Example:- fopen(“E:\\cprogram\\new.txt”,”w”);
• 2) 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);
• fcloseall () -
• function closes all open streams except stdin , stdout ,
stderr (and, in MS-DOS, _stdaux and _stdprn ). It also closes
and deletes any temporary files created by tmpfile . In both
functions, all buffers associated with the stream are flushed
prior to closing.
• 3) Reading a data from file:- To write the file, we must open the filein a mode
that support writing. C provide following set of functions to read data from a
file.
• Fgetc()
• Fgets()
• Fscanf()
• Fread()
• 4) Writing data to file:- Wriritng a program output or some of the variable has
to be saved to a storage location on the file system, the data has to be written
to a file.
• Fputc()
• Fputs()
• Fprintf()
• Fwrite()
Input/output file operation on file:-
• They are broadly classified into-
1)High level files I/O functions
2)Low level files I/O functions
• Unformatted file I/o Functions-
putw()- putw function is used to write an integer into a file.
Syntax: putw(I,fp); where I is interger value, fp-file pointer
Ex:- int putw(int number, FILE *fp);
getw()- getw function is used to read an integer into a file.
Syntax: getw(fp); where fp-file pointer
Ex:- int getw(FILE *fp);
write a program to display the value of array using getw() and putw(
#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.
• fgetc() is used to read characters from the file
Syntax: Fgetc(fp);
Fp is file pointer.
#include <stdio.h>
int main() {
FILE *file;
char ch;
// Open the file in write mode
file = fopen("output.txt", "w");
if (file == NULL) {
printf("Could not create file\n");
return 1;
}
// Get characters from the user and write them to the file
printf("Enter characters. Enter '#' to end:\n");
while ((ch = getchar()) != '#') {
fputc(ch, file);
}
// Close the file
fclose(file);
printf("File created successfully.\n");
return 0;
}
• Output:- Hello world
String Oriented function
The fputs() function writes a line of characters into file. It
outputs string to a stream.
Syntax: fputs(buffer,fp);
Where buffer is name of character array. And fp is pointer.
fgets()- used to read a string from a file.
Syntax:- fgets(buffer,siza,fp);
Buffer- name of character array.
Size is an integer.
Fp is pointer.
#include <stdio.h>
int main ()
{
FILE *fp; char str[60];
/* opening file for reading */
fp = fopen("file.txt" , "r");
if(fp == NULL)
{
perror("Error opening file");
return(-1);
}
if( fgets (str, 60, fp)!=NULL )
{
/* writing content to stdout */
puts(str);
}
fclose(fp);
return(0);
}
Let us assume, we have a text file file.txt, which has the following content. This file will be used as an input for our
example program −
We are in 2024.
Formatted file I/O function:-
• Fprintf- used to write multiple data item which may or may not be of
different type to a file
Syntax : fprintf(fp,”control string”, Arguments list);
• Fscanf :-used to read multiple data item which may or may not be of
different type to a file
Syntax : fscanf(fp,”control string”, Arguments list);
• Fwrite:- used to write block of data.
Syntax:- fwrite( buffer_address, size, count, file_operator);
• Fread:- used to read bytes from file.
Syntax:- fwrite( buffer_address, size, count, file_operator);
What is errno:- whenever a function call is made in c language a
variable named errno is associated with it.
-it is a global variable which can be used to identify which type of error
encountered while function execution. Based on its value.
Library function for error handling:-
1) feof()
The feof() function is used to check whether end-of-file indicator is set for a file steam.
Syntax
int feof(FILE *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
int feof(FILE *stream);
Parameters
stream: 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.