Introduction

We have been taking data input or output from user on console using functions like printf(), scanf(), puts(), gets() etc. We know that the output on console is not permanent. We cannot store anything there. So for that we need something that could store the output and for the same we have files.

Types of files

• Text files- which a user can easily read and understand from it like .cpp or .c files

• Binary files- which are not readable and can’t be understood by the user because it contains binary data or binary characters like .obj or .exe files. It is mainly for computers.

FILE Operations

There are number of functions that can be performed whiles working with files. These are
• Creating a new file
• Opening a File
• Reading from a file
• Writing to a file
• Appending to a file
• Moving to a specific location in file (seeking)
• Closing a file

Working with Files

In order to perform all the functions mentioned above we firstly need to create a pointer of FILE type. This pointer will act as a communication mode between the program and the file.

Example 1

FILE *fptr ; 				 // declaring a file pointer
		

Creating and Opening a File

To open a file we have an in-built function called fopen()

Syntax for using fopen() function:
fopen(<filename>, <mode>);

• Filename has to be preferably with its path. If path not given then it will try to open the file in present working directory.
• Mode is basically the mode in which we want to open the file like only in read mode , writ mode etc.
• fopen() function returns a pointer which we need capture or store. That’s the reason why I have asked to declare a file pointer for working with files.

File Modes

Mode Meaning Comments
r Open for reading only.  If the file does not exist, fopen() returns NULL i.e. 0 address.
 If the file exists, fopen() will return a reference value.
w Open for writing only.
(also used for creating new file)
 If the file exists, its contents are overwritten.
 If the file does not exist, a new file will be created.
r+ Open for both reading and writing  If the file does not exist, fopen() returns NULL i.e. 0 address
 Cannot create a new file in this mode
w+ Open for both reading and writing.  If the file exists, its contents are overwritten.
 If the file does not exist, a new file will be created.
a Open for appending. i.e., Data is added at end of file.  If the file does not exist, a new file will be created
a+ Open for both reading and appending.  If the file does not exist, a new file will be created.

Program 1

Program to check whether a file exist or not

#include<stdio.h>
#include<conio.h>

void main()
{
FILE *fptr;
fptr=fopen("abc.txt","r");		//here the file abc.txt should exist in the present        
 		//working directory
printf("%s", fptr);
getch();

}
		

• If the file does not exits fopen() will return NULL pointer i.e. a pointer which points to address 0. Output of above program would be-

(null) //0 address

• If the file exists fopen() will return the file descriptor. To see the file descriptor modify the 9th line of above program to

printf(“%d”,fptr);

Closing a FILE

A file opened should also be closed at the end of the program after the task to be performed using file is over. To close the file we have a function fclose()

• fclose() returns 0 if file is successfully closed.
• else EOF or -1 is returned if there is error in closing the file. EOF is a constant defined in stdio.h header file.

Syntax for using fclose() function:
fclose(<file pointer>);

Program 2

Program determining opening and closing operation on a file

#include<stdio.h>
#include<conio.h>

void main()
{
clrscr();
FILE *fptr;
fptr=fopen("ABC.C","rb");
printf("%d\n",fptr);


int i=fclose(fptr);			// returns 0 or -1

printf("%d",i);     

getch();

}
		

Writing to a FILE

We have been using printf() function to print something on the standard output window. Similar to printf() we have a function fprintf() for writing to a file.

Syntax for using fprintf()
Fprintf(<file pointer>, <”text to be written to file”>,….);

Program 3

//Program writing to a file using fprintf() function

#include<stdio.h>
#include<conio.h>

void main()
{
clrscr();
FILE *fptr;
fptr=fopen("ABC.TXT","w");
printf("%d\n",fptr);

fprintf(fptr,"I am working on File Handling operations. \n Lets print the Value in File Pointer and it is %d", fptr);

int i=fclose(fptr);

printf("%d",i);

getch();

}
		

Here the file opening mode used by me is “w” i.e. write mode in which If the file exists, its contents are overwritten. If the file does not exist, it will be created and content will be overwritten. If we want to append the text to file use “a” i.e. append mode.

Reading from a FILE

For reading from a file we have number of special functions like fscanf() similar to scanf(), fgets(), fgetc() etc.

Syntax for using fscanf()
fscanf(<file pointer>, <”format specifier”>,<string variable>);

#include<stdio.h>
#include<conio.h>

void main()
{
clrscr();
FILE *fptr;
char str[100];
fptr=fopen("ABC.TXT","r");
printf("%d\n",fptr);
do
{
fscanf(fptr,"%s",str);
printf("%s ",str);
}
while(!feof(fptr));
fclose(fptr);


getch();

}

		

• fscanf() stops at whitespace, i.e. it reads string only up to it encounter a space.
• The C library function int feof(FILE *stream) tests the end-of-file indicator for the given stream.
• feof(FILE *) returns 0 unless it encounters EOF-End of the file indicator else it will return -1.

Program 4

Program to read a file character by character

  #include<stdio.h>
#include<conio.h>

void main()
{
clrscr();
FILE *fptr;
char ch;
fptr=fopen("ABC.TXT","r");

ch=fgetc(fptr) ;

while(ch!=EOF)
{
printf("%c",ch);
ch=fgetc(fptr);
}

fclose(fptr);


getch();

}

		

Syntax for using fgets()

fgets(<string variable>,<Maximum no. of characters to be read>,<file pointer>)

• while using fgets() if a line consists of character less than maximum length specified then fgets() will read only upto ‘\n’ newline character and store the string into string variable.

• fgets() overcomes the problem fscanf() faces when the length of char array is smaller the actual length of the strength being read before whitespace.

Program 5

Program illustrating the fgets() function

#include<stdio.h>
#include<conio.h>

void main()
{
clrscr();
FILE *fptr;

char str[7];
fptr=fopen("ABC.TXT","r");
printf("%d\n",fptr);
do
{
fgets(str,10,fptr);
printf("%s",str);

}
while(!feof(fptr));
fclose(fptr);


getch();

}
	

Moving to a Specific Location in File

fseek () is a function which moves the file pointer to a specific function.

Syntax for using fgets()
fseek(<file pointer>,<offset value>,<reference position>);

• offset value- it is the no. of bytes to offset from the referred position
• Reference position- it the position from where the offset is added. It is specified by using one of the following built-in library constants.

 SEEK_SET – Beginning of a file
 SEEK_CUR – current position of the file pointer
 SEEK_END – End of the file

Program 6

Program illustrating the fseek() function

#include<stdio.h>
#include<conio.h>

void main()
{
clrscr();
FILE *fptr;
char str[7];
fptr=fopen("ABC.TXT","r");
printf("%d\n",fptr);

fseek(fptr,7,SEEK_SET); // 7 bytes will be offset
do
{
fgets(str,10,fptr);
printf("%s",str);

}
while(!feof(fptr));
fclose(fptr);


getch();

}
  
		

Email Address

If you have any training enquiry then send mail at info@techaltum.com.