Introduction:
FILES
Introduction:
Reading, processing and writing of data are the three essential functions of a computer program.
Most programs take some data as input and display the processed data, often known as result.
Unlike other high-level languages, C does not have any built-in input/output statements as part of
its syntax.
A library of functions is supplied to perform these (I/O) operations. The I/O library functions are
listed the “header” file <stdio.h>. You do not need to memorize them, just be familiar with them.
The I/O library functions can be classified into two broad categories:
Console I/O functions - functions to receive input from keyboard and write output to VDU.
File I/O functions – functions to perform I/O operations on a floppy disk or a hard disk.
Console I/O Functions
Console I/O refers to the operations that occur at the keyboard and screen of the computer.
Because input and output to the console is such a common affair, a subsystem of the ANSI I/O file
system was created to deal exclusively with console I/O. Technically, these functions direct their
operations to the standard input (stdin) and standard output (stdout) of the system.
Console I/O functions are further divided into two categories:
1. Formatted console I/O functions —printf/scanf.
2. Unformatted console I/O functions – getchar, putchar etc.
Disadvantages
This works fine as long as the data is small. Real-world problems involve large volumes of data
and in such situations, Console I/O functions pose two major problems,
1. It becomes time consuming to handle large amount of data.
2. Entire data is lost when either the program is terminated or the computer is turned off.
At these times, it becomes necessary to store the data in a manner that can be later retrieved and
displayed. This medium is usually a ‘file’ on the disk. This chapter discusses how file I/O operations
can be performed.
FILES
A file is an external collection of related data treated as a unit. The primary purpose of a file is to
keep record of data. Record is a group of related fields. Field is a group of characters they convey
meaning.
Files are stored in auxiliary or secondary storage devices. The two common forms of secondary
storage are disk (hard disk, CD and DVD) and tape. Each file ends with an end of file (EOF) at a
specified byte number, recorded in file structure.
A file must first be opened properly before it can be accessed for reading or writing. When a file is
opened an object (buffer) is created and a stream is associated with the object.
SHIVAKUMAR MECS 1
FILES
Buffer
When the computer reads, the data move from the external device to memory; when it writes, the
data move from memory to the external device. This data movement often uses a special work
area known as buffer. A buffer is a temporary storage area that holds data while they are being
transferred to or from memory. The primary purpose of a buffer is to synchronize the physical
devices with a program's need.
File Name
File name is a string of characters that make up a valid filename. Every operating system uses a
set of rules for naming its files. When we want to read or write files, we must use the operating
system rules when we name a file. The file name may contain two parts, a primary name and an
optional period with extension.
Example: [Link]
program.c
File Information Table
A program that reads or write files needs to know several pieces of information, such as name of
the file, the position of the current character in the file, etc..,
C has predefined structure to hold this information. The stdio.h header file defines this file
structure; its name is FILE. When we need a file in our program, we declare it using the FILE type.
STREAM
A stream is a general name given to a flow of data. All input and output is performed with streams.
A "stream" is a sequence of characters organized into lines. Each line consists of zero or more
characters and ends with the "newline" character.
ANSI C standards specify that the system must support lines that are at least 254 characters in
length (including the new line character).
A stream can be associated with a physical device, terminal, or with the file stored in memory.
The following Figure 6.1 illustrates the data flow between external device (C Program), buffer and
file.
Buffer
//C Program
abcdefg
……..
………..
Stream
abcdefg
File
Fig: Data Flow
C programming language supports two types of files and they are as follows...
• Text Files (or) ASCII Files
• Binary Files
SHIVAKUMAR MECS 2
File Operations in C
Text File (or) ASCII File - The file that contains ASCII codes of data like digits, alphabets and
symbols is called text file (or) ASCII file. Text files are the normal .txt files that you can easily create
using Notepad or any simple text editors. It consisting of collection of stream of characters that
can be processed sequentially and in forward direction only
Binary File - The file that contains data in the form of bytes (0's and 1's) is called as binary file.
Generally, the binary files are compiled version of text files. Binary files are mostly the .bin files in
your computer. Instead of storing data in plain text, they store it in the binary form (0's and
1's).They can hold higher amount of data, are not readable easily and provides a better security
than text files.
Text File Binary File
Data is human readable characters. Data is in the form of sequence of bytes.
Each line ends with a newline character. There are no lines or newline characters.
EOF indicates end of the file. An feof() is a function to indicates end of the
file.
File reading is possible in forward direction File reading is possible in any direction.
only.
They take minimum effort to maintain, are They can hold higher amount of data, are not
easily readable and provide least security and readable easily and provides a better security
takes bigger storage space. than text files.
Ex: C file Ex: obj file
File Operations in C
The following are the operations performed on files in c programming langauge...
• Creating (or) Opening a file
• Reading data from a file
• Writing data into a file
• Closing a file
All the above operations are performed using file handling functions available in C. We discuss file
handling functions in the
Creating (or) Opening a file
Before we perform any operations on a file, we need to open it. We do this by using a file pointer.
The type FILE defined in stdio.h allows us to define a file pointer. Then you use the function fopen()
for opening a file.
To create a new file or open an existing file, we need to create a file pointer of FILE type. Following
is the sample code for creating file pointer.
File *file_pointer ;
We use the pre-defined method fopen() to create a new file or to open an existing file. There are
different modes in which a file can be opened. Consider the following code...
Declaration: FILE *fopen (const char *filename, const char *mode)
SHIVAKUMAR MECS 3
File Operations in C
fopen() function is used to open a file to perform operations such as reading, writing etc. In a C
program, we declare a file pointer and use fopen() as below. fopen() function creates a new file if
the mentioned file name does not exist.
FILE *fp;
fp=fopen (“filename”, ”‘mode”);
Where,
• fp – file pointer to the data type “FILE”.
• filename – the actual file name with full path of the file.
• mode – refers to the operation that will be performed on the file.
o Example: r, w, a, r+, w+ and a+.
In C programming language, there different modes are available to open a file and they are shown
in the following table.
S. No. Mode Description
1 r Opens a text file in reading mode.
2 w Opens a text file in wirting mode.
3 a Opens a text file in append mode.
4 r+ Opens a text file in both reading and writing mode.
5 w+ Opens a text file in both reading and writing mode. It set the cursor position to
the begining of the file if it exists.
6 a+ Opens a text file in both reading and writing mode. The reading operation is
performed from begining and writing operation is performed at the end of the file.
Note - The above modes are used with text files only. If we want to work with binary files we use
rb, wb, ab, rb+, wb+ and ab+.
Reading from a file
The reading from a file operation is performed using the following pre-defined file handling
methods.
1. getc()
2. getw()
3. fscanf()
4. fgets()
5. fread()
getc()
variable= getc( *file_pointer ):
This function is used to read a character from specified file which is opened in reading mode. It
reads from the current position of the cursor. After reading the character the cursor will be at next
character.
SHIVAKUMAR MECS 4
File Operations in C
Example Program to illustrate getc() in C.
#include<stdio.h>
#include<stdlib.h>
int main( ) {
FILE *fp;
char ch;
fp = fopen("[Link]","r");
if(fp==NULL)
{
printf(Error!! File can’t be opened\n”);
exit(0);
}
printf("Reading character from the file: %c\n",getc(fp));
ch = getc(fp);
printf("ch = %c", ch);
fclose(fp);
return 0;
}
OUTPUT:
getw( )
Integer_variable=getw( *file_pointer );
This function is used to read an integer value form the specified file which is opened in reading
mode. If the data in file is set of characters then it reads ASCII values of those characters.
Example Program to illustrate getw() in C.
#include<stdio.h>
#include<stdlib.h>
int main(){
FILE *fp;
int i,j;
fp = fopen("[Link]","w");
putw(65,fp); // inserts A
putw(97,fp); // inserts a
fclose(fp);
fp = fopen("[Link]","r");
if(fp==NULL)
SHIVAKUMAR MECS 5
File Operations in C
{
printf(Error!! File can’t be opened\n”);
exit(0);
}
i = getw(fp); // reads 65 - ASCII value of A
j = getw(fp); // reads 97 - ASCII value of a
printf("SUM of the integer values stored in file = %d", i+j); // 65 + 97 = 162
fclose(fp);
return 0;
}
OUTPUT
scanf( ):
scanf( *file_pointer, typeSpecifier, &variableName );
This function is used to read multiple datatype values from specified file which is opened in
reading mode.
Example Program to illustrate fscanf() in C.
#include<stdio.h>
#include<stdlib.h>
int main(){
char str1[10], str2[10], str3[10];
int year;
FILE * fp;
fp = fopen ("[Link]", "w+");
if(fp==NULL)
{
printf(Error!! File can’t be opened\n”);
exit(0);
}
fputs("We are in 2016", fp);
rewind(fp); // moves the cursor to begining of the file
fscanf(fp, "%s %s %s %d", str1, str2, str3, &year);
printf("Read String1 - %s\n", str1 );
printf("Read String2 - %s\n", str2 );
printf("Read String3 - %s\n", str3 );
printf("Read Integer - %d", year );
fclose(fp);
return 0;
SHIVAKUMAR MECS 6
File Operations in C
}
OUTPUT:
fgets( ):
fgets( variableName, numberOfCharacters, *file_pointer );
This method is used for reading a set of characters from a file which is opened in reading mode
starting from the current cursor position. The fgets() function reading terminates with reading
NULL character.
Example Program to illustrate fgets() in C.
#include<stdio.h>
int main(){
FILE *fp;
char *str;
fp = fopen ("[Link]", "r");
if(fp==NULL)
{ Output
printf(Error!! File can’t be opened\n”);
exit(0);
}
fgets(str,6,fp);
printf("str = %s", str);
fclose(fp);
return 0;
}
fread( ):
fread( source, sizeofReadingElement, numberOfCharacters, FILE *pointer )
This function is used to read specific number of sequence of characters from the specified binary
file which is opened in reading mode.
Example Program to illustrate fgets() in C.
#include<stdio.h>
int main(){
FILE *fp;
char *str;
fp = fopen ("[Link]", "r");
if(fp==NULL)
SHIVAKUMAR MECS 7
File Operations in C
{
printf(Error!! File can’t be opened\n”);
exit(0);
}
fread(str,sizeof(char),5,fp);
str[strlen(str)+1] = 0;
printf("str = %s", str);
fclose(fp);
return 0;
}
Output
Writing into a file
The writing into a file operation is performed using the following pre-defined file handling
methods.
1. putc()
2. putw()
3. fprintf()
4. fputs()
5. fwrite()
putc( ):
putc( char, *file_pointer )
This function is used to write/insert a character to the specified file when the file is opened in
writing mode.
Example Program to illustrate putc() in C. OUTPUT:
#include<stdio.h>
int main(){
FILE *fp;
char ch;
fp = fopen("C:/TC/EXAMPLES/[Link]","w");
putc('A',fp);
ch = 'B';
putc(ch,fp);
fclose(fp);
return 0;
}
SHIVAKUMAR MECS 8
File Operations in C
putw( ):
putw( int, *file_pointer )
This function is used to writes/inserts an integer value to the specified file when the file is opened
in writing mode.
Example Program to illustrate putw() in C. OUTPUT
#include<stdio.h>
#include<stdlib.h>
int main(){
FILE *fp;
int i;
fp = fopen("[Link]","w");
if(fp==NULL)
{
printf(Error!! File can’t be opened\n”);
exit(0);
}
putw(66,fp);
i = 100;
putw(i,fp);
fclose(fp);
return 0;
}
fprintf( ):
fprintf( *file_pointer, "text" )
This function is used to writes/inserts multiple lines of text with mixed data types (char, int, float,
double) into specified file which is opened in writing mode.
Example Program to illustrate "fprintf()" in C. OUTPUT
#include<stdio.h>
#include<stdlib.h>
int main(){
FILE *fp;
char *text = "\nthis is example text";
int i = 10;
fp = fopen("[Link]","w");
if(fp==NULL)
{
printf(Error!! File can’t be opened\n”);
exit(0);
}
fprintf(fp,"This is line1\nThis is line2\n%d", i);
fprintf(fp,text);
fclose(fp);
SHIVAKUMAR MECS 9
File Operations in C
return 0;
}
fputs( ):
fputs( "string", *file_pointer ) - TThis method is used to insert string data into specified file which
is opened in writing mode.
Example Program to illustrate fputs() in C.
#include<stdio.h>
#include<stdlib.h>
int main(){
FILE *fp;
char *text = "\nthis is example text";
fp = fopen("[Link]","w");
if(fp==NULL)
{
printf(Error!! File can’t be opened\n”);
exit(0);
}
fputs("Hi!\nHow are you?",fp);
fclose(fp);
return 0;
}
Output
fwrite( ):
fwrite( “StringData”, sizeof(char), numberOfCharacters, FILE *pointer )
This function is used to insert specified number of characters into a binary file which is opened in
writing mode.
Example Program to illustrate fwrite() in C.
OUTPUT:
#include<stdio.h>
SHIVAKUMAR MECS 10
File Operations in C
#include<stdlib.h>
int main(){
FILE *fp;
char *text = "Welcome to C Language";
fp = fopen("[Link]","wb");
if(fp==NULL)
{
printf(Error!! File can’t be opened\n”);
exit(0);
}
fwrite(text,sizeof(char),5,fp);
fclose(fp);
return 0;
}
Closing a file
Closing a file is performed using a pre-defined method fclose().
fclose( *f_ptr )
The method fclose() returns '0'on success of file close otherwise it returns EOF (End Of File).
If a program terminates, it automatically closes all opened files. But it is a good programming habit
to close any file once it is no longer needed. This helps in better utilization of system resources,
and is very useful when you are working on numerous files simultaneously. Some operating
systems place a limit on the number of files that can be open at any given point in time.
Cursor Positioning Functions in Files
C programming language provides various pre-defined methods to set the cursor position in files.
The following are the methods available in c, to position cursor in a file.
1. ftell()
2. rewind()
3. fseek()
ftell( )
ftell( *file_pointer )
Function ftell() returns the current position of the file pointer in a stream. The return value is 0 or
a positive integer indicating the byte offset from the beginning of an open file. A return value of -1
indicates an error.
Example Program to illustrate ftell() in C.
#include<stdio.h>
#include<stdlib.h>
int main(){
FILE *fp;
int position;
fp = fopen ("[Link]", "r");
if(fp==NULL)
SHIVAKUMAR MECS 11
File Operations in C
{
printf(Error!! File can’t be opened\n”);
exit(0);
}
position = ftell(fp);
printf("Cursor position = %d\n",position);
fseek(fp,5,0);
position = ftell(fp);
printf("Cursor position = %d", position);
fclose(fp);
return 0;
}
Output
rewind( ):
rewind( *file_pointer );
This function is used reset the cursor position to the beginning of the file.
Example Program to illustrate rewind() in C.
#include<stdio.h>
#include<stdlib.h>
int main(){
FILE *fp;
int position;
fp = fopen ("[Link]", "r");
if(fp==NULL)
{
printf(Error!! File can’t be opened\n”);
exit(0);
}
position = ftell(fp);
printf("Cursor position = %d\n",position);
fseek(fp,5,0);
position = ftell(fp);
printf("Cursor position = %d\n", position);
rewind(fp);
SHIVAKUMAR MECS 12
File Operations in C
position = ftell(fp);
printf("Cursor position = %d", position);
fclose(fp);
return 0;
}
Output
fseek( ):
fseek( *file_pointer, long int offset, fromPosition );
This function positions the next I/O operation on an open stream to a new position relative to the
current position.
•
Here fp is the file pointer of the stream on which I/O operations are carried on.
•
offset is the number of bytes to skip over. The offset can be either positive or negative,
denting forward or backward movement in the file.
• From position is the position in the stream to which the offset is applied, this can be one of
the following constants :
1) SEEK_SET : offset is relative to beginning of the file
2) SEEK_CUR : offset is relative to the current position in the file
3) SEEK_END : offset is relative to end of the file
This function is used to set the cursor position to the specific position. Using this function we can
set the cursor position from three different position they are as follows.
• from beginning of the file (indicated with 0)
• from current cursor position (indicated with 1)
• from ending of the file (indicated with 2)
Example Program to illustrate fseek() in C.
#include<stdio.h>
#include<stdlib.h>
int main(){
FILE *fp;
int position;
fp = fopen ("[Link]", "r");
if(fp==NULL)
{
printf(Error!! File can’t be opened\n”);
exit(0);
SHIVAKUMAR MECS 13
File Operations in C
}
position = ftell(fp);
printf("Cursor position = %d\n",position);
fseek(fp,5,0);
position = ftell(fp);
printf("Cursor position = %d\n", position);
fseek(fp, -5, 2);
position = ftell(fp);
printf("Cursor position = %d", position);
fclose(fp);
return 0;
}
Output
File Status Functions
feof( ):
The macro feof() is used for detecting whether the file pointer is at the end of file or [Link] returns
nonzero if the file pointer is at the end of the file otherwise it returns zero.
The feof() function indicates whether the end-of-file flag is set for the given stream. The end-offile
flag is set by several functions to indicate the end of the file. The end-of-file flag is cleared by calling
the rewind(), fsetpos(), fseek(), or clearerr() functions for this stream
Syntax: feof(fptr);
Where fptr is a file pointer .
ferror( )
The macro ferror() is used for detecting whether an error occur in the file on filepointer or [Link]
returns the value nonzero if an error,otherwise it returns zero.
The ferror() function tests for an error in reading from or writing to the given stream. If an error
occurs, the error indicator for the stream remains set until you close stream, call the rewind()
function, or call the clearerr() function. The ferror() function returns a nonzero value to indicate
an error on the given stream. A return value of 0 means that no error has occurred.
Syntax: ferror(fptr);
perror()
perror() function displays the string you pass to it, followed by a colon, a space, and then the
textual representation of the current errno value.e fptr is a file pointer.
The perror() function prints an error message to stderr. If string is not NULL and does not point
to a null character, the string pointed to by string is printed to the standard error stream, followed
SHIVAKUMAR MECS 14
File Operations in C
by a colon and a space. The message associated with the value in errno is then printed followed by
a new-line character.
To produce accurate results, you should ensure that the perror() function is called immediately
after a library function returns with an error; otherwise, subsequent calls might alter the errno
value.
Syntax: void perror(const char*str);
clearerr()
Syntax: void clearerr (FILE *stream);
The clearerr() function resets the error indicator and end-of-file indicator for the specified stream.
Once set, the indicators for a specified stream remain set until your program calls the clearerr()
function or the rewind() function. The fseek() function also clears the end-of-file indicator. There
is no return value.
Example Program:
#include <stdio.h>
int main () {
FILE *fp;
int c;
fp = fopen("[Link]","r");
if(fp == NULL) {
perror("Error in opening file");
return(-1);
}
while(1)
{
c = fgetc(fp);
if( feof(fp) )
break ;
printf("%c", c);
}
fclose(fp);
return(0);
}
SHIVAKUMAR MECS 15