0% found this document useful (0 votes)
5 views5 pages

Problem Solving Using C Notes 5

The document provides an overview of file handling in C, detailing the types of files, advantages of using files, and the functions available for file operations. It explains how to define, open, read, and write files using various library functions from stdio.h, including fopen, fclose, getc, putc, fread, fwrite, and others. Additionally, it covers random access to files and the use of EOF and feof functions to manage file reading operations.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views5 pages

Problem Solving Using C Notes 5

The document provides an overview of file handling in C, detailing the types of files, advantages of using files, and the functions available for file operations. It explains how to define, open, read, and write files using various library functions from stdio.h, including fopen, fclose, getc, putc, fread, fwrite, and others. Additionally, it covers random access to files and the use of EOF and feof functions to manage file reading operations.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

1.

Introduction to Files in C (File handling)

A file is a collection of data stored on secondary storage (hard disk). In other words, file is a
collection of numbers, symbols & text placed onto the secondary devices like hard disk, pen drive,
compact disk etc.

Files allow us to store data / information permanently, and to access and alter that information
whenever necessary.

In C, an extensive set of library functions are available in stdio.h, for naming a file, opening a file,
reading data from a file, writing data to a file, and closing a file.

A file can be considered as a stream of characters. Stream-oriented data files can be subdivided into
two categories.

• In the first category are text files, consisting of consecutive characters.


• The second category of stream-oriented data files, often referred to as unformatted data
files, organizes data into blocks containing contiguous bytes of information. These blocks
represent more complex data structures, such as arrays and structures.

Advantages of Files

• Permanent data storage


• Large data handling
• Data sharing between programs
• Backup and recovery

Defining & opening a file:

To work with a file, you must define a pointer of type FILE (defined in stdio.h). This pointer acts as a
communication bridge between your program and the file stored on the disk.

Syntax for declaring and opening a file: FILE *fp;

Note: When working with a data file, the first step is to establish a buffer area, where information is
temporarily stored while being transferred between the computer’s memory and the data file. This
buffer area allows information to be read from or written to the data file.

fopen()
The library function fopen is used to open a file. Its syntax is
fp = fopen(“filename”, “mode”);
here filename represents name of the data file, mode represents the purpose of opening
this file (i.e, for reading, writing or appending, etc.). Mode can be one of the following (for text files)

Mode Description
R Opens a text file only for reading

PRESIDENCY UNIVERSITY, IC. M. CHANDRA SEKHAR 1


W Opens a text file only for writing

A Opens a text file for appending

r+ Opens a text file for reading and writing

w+ Opens a text file for reading and writing

a+ Append a text file for read/write

For binary files letter ‘b’ is added. For example “rb” for opening a binary file only for reading, “wb”
for opening a binary file only for writing.

Return Value:
• If the file is opened successfully, fopen() returns a file pointer to it.
• If the file is not opened, then returns NULL.

Example:
if (fp == NULL) {
printf("The file is not opened.");
}
Note:
1. When the mode is ‘writing’, a file with the specified name is created if the file does not exist.
The contents are deleted, if the file already exists.

2. When the purpose is ‘appending’, the file is opened with the current contents safe. A file
with the specified name is created if the file does not exist.

3. Many recent compilers include additional modes of operation. They include:


r+ The existing file is opened to the beginning for both reading and writing.
w+ Same as w except both for reading and writing.
a+ Same as a except both for reading and writing.

fclose() : File must be closed after performing operations on it. The fclose() function closes an opened
file.
Its syntax is fclose (fp);

Note: The fclose() function actually flushes any data still pending in the buffer to the file, closes the
file, and releases any memory used for the file.

Input/Output Operations on Files:


Once a file is opened, reading out of or writing to it is accomplished using the standard I/O routines

putc() and getc() functions:

getc() : It is used to read a single character to a file (whose file pointer is fp). Its syntax is
c = getc(fp);
here c is a character variable.

putc() It is used to write a single character to a file. Its syntax is

PRESIDENCY UNIVERSITY, IC. M. CHANDRA SEKHAR 2


putc(c, fp);
here c is a character variable.

Note : The file pointer moves by one character position for every operation of getc or putc. The getc
will return an end-of-file marker EOF, when end of the file has been reached. Therefore, the reading
should be terminated when EOF is encountered

Working with Strings: fputs( ) and fgets( )


fgets( ) and fputs( ), which read and write character strings from and to a disk file. These functions
similar to putc( ) and getc( ), but instead of reading or writing a single character, they read or write
strings.

fputs() function writes the string to the specified stream. Its syntax is
fputs(string, file_pointer);

fgets() function reads a string (line) from a file (or input stream) including spaces. Its syntax is

fgets(string, size, file_pointer);


here size is the maximum number of characters to be read from the file.

putw() and getw() functions:

putw(): It is used to write an integer to a file. Its syntax is


putw(variable, fp);
here variable is an integer variable.

getw(): It is used to read an integer from a file. Its syntax is


variable= getw(fp);
here variable is an integer variable.

Note : The getw and putw are integer-oriented functions, would be useful when we deal with only
integer data.

The fprintf and fscanf functions:

The functions fprintf and fscanf perform I/O operations (mixed data values) that are similar to printf
and scanf functions (except of course that they work on files).

fprintf() is used to write a formatted string (data) to a file.

Its syntax is
fprintf(fp, “control string”, list);

Example : fprintf(fp, “%s %d %f”, name, age, cgpa);

fscanf() is used to read a formatted string from a file. Its syntax is

fscanf(fp, “control string”, list);

Example : fscanf(fp, “%s %d %f”, name, &age, &cgpa);

PRESIDENCY UNIVERSITY, IC. M. CHANDRA SEKHAR 3


fread() and fwrite() Binary File Operations:

fread() and fwrite() functions are used for binary file operations to read and write entire structures
or data blocks at once directly to and from a file (disk).

The fwrite() function is used to write a block of data (binary) to a file.

Note: Unlike fprintf, it doesn't convert numbers to text; it saves the exact bit pattern from memory.

Its syntax is

fwrite(&structure_variable, sizeof(structure), integer, file_pointer);

Example : fwrite(&s1, sizeof(struct student), 1, fp);

In the above syntax the first argument is the address of the structure to be written onto the disk, the
second argument is the size of the structure in bytes, the third argument is the number of such
structures (records) that the user wants to write at one time and the last argument is the file pointer.
The fread() function reads a block of data from a binary file and stores it in a memory location.

Its syntax is

fread (&structure_variable, sizeof(structure), integer, file_pointer);

Example : fread(&s1, sizeof(struct student), 1, fp);

Random Access to Files:


So far we have discussed file functions that are useful for reading and writing data sequentially.
If we want to access a particular record (part of a file), C supports some functions for random access
file processing.

C provides three functions to access data randomly. They are: ftell() fseek() and rewind().

ftell() : Returns (long integer value) the current position of the file pointer.

Syntax
long int ftell(FILE *fp);

Example)
long int n;
n=ftell(fp);

rewind() function : Moves the file pointer to the beginning of the file (resets the position to the start
of the file).

The syntax is
rewind(fp);

fseek function is used to move the file pointer position to a specific location within the file.
It syntax is
fseek(file_ptr, offset, position);

PRESIDENCY UNIVERSITY, IC. M. CHANDRA SEKHAR 4


file_ptr is a pointer to the file concerned
offset is a number or variable of type long, and position is an integer number. The offset specifies
the number of positions (bytes) to be moved from the location specified by position.
The position (reference position) can take one of the following three values:
Constant Meaning
SEEK_SET or 0 Beginning of file
SEEK_CUR or 1 Current position
SEEK_END or 2 End of file

Example :

Operation Meaning
fseek(fp, 0, SEEK_SET) Move to beginning of file
fseek(fp, n, SEEK_SET) Move n bytes from beginning
fseek(fp, 0, SEEK_END) Move to end of file
fseek(fp, -n, SEEK_END) Move n bytes backward from end
fseek(fp, n, SEEK_CUR) Move n bytes forward from current position
fseek(fp, -n, SEEK_CUR) Move n bytes backward from current position

EOF and feof() :

EOF (End Of File) is a special constant (defined in stdio.h, Usually has value -1) used to indicate,
no more data is available to read from a file
Example :
while ((ch = fgetc(fp)) != EOF)
{
printf("%c", ch);
}

feof() is a function checks whether the end of file has been reached.

Return Value

• Returns non-zero (true) → if EOF reached


• Returns 0 (false) → if not reached

Example: while (!feof(fp))


{
-------------
-------------
}

PRESIDENCY UNIVERSITY, IC. M. CHANDRA SEKHAR 5

You might also like