FILES in C Programming Language
FILES in C Programming Language
Definition: FILE is a predefined structure data type which is defined in library file called
stdio.h. (OR)
FILE is a set of records that can be accessed through a set of library functions.
Syntax:
FILE *filepointerobject;
Example:
FILE *fp; // where FILE is a keyword and “fp” is a file pointer object
C supports a number of functions that have the ability to perform basic file operations, which
include:
1. Naming a file
2. Opening a file
3. Reading from a file
4. Writing data into a file
5. Closing a file
File operation functions in C:
Function Name Operation
fopen() is a predefined file handling function which is used to open already existing file or to
create a file. It accepts two strings, the first is the name of the file, and the second is the mode in
which it should be opened. The general format of the function used for opening a file is as
follows:
Syntax:
FILE *filepointer;
filepointer=fopen(“filename.filetype”,”mode”);
Example: FILE *fp;
fp= fopen(“gitam.txt”,”w”);
where gitam.txt is file name.
where ‘w’ is write mode.
Note: The function fopen( ) is compulsory for the files to do any operations, without
fopen( ), we cannot perform operations on files.
S.No. Mode Description
1. “r” Open for reading. The precondition is file must exist. Otherwise
function returns Null Value.
2. “w” Open for writing. If file already exists, its contents are overwritten.
Otherwise a new file is created. The function returns NULL if it is unable
to create the file. File cannot created for the reasons such as not having
access permission, disk full, having write protect etc.,.
3. “a” Open for appending. If file already exist, the new contents are appended.
Otherwise, a new file is created. The function return NULL if it is unable
to create the file.
4. “r+” Open for both reading and writing. The file must exists.
5. “w+” Open for both reading and writing. Contents written over.
6. “a+” Open for reading and appending. If file is not existing the file is created.
Where fp id is a file pointer associated with a file that has been opened for writing. The control
string is file output specifications list may include variable, constant and string.
⮚ When we have finished reading from the file, we need to close it. This is done using the
function fclose through the statement, fclose( fp );
⮚ During a write to a file, the data written is not put on the disk immediately. It is stored in
a buffer. When the buffer is full, all its contents are actually written to the disk. The
process of emptying the buffer by writing its contents to disk is called flushing the buffer.
⮚ Closing the file flushes the buffer and releases the space taken by the FILE structure
which is returned by fopen. Operating System normally imposes a limit on the number of
files that can be opened by a process at a time. Hence, closing a file means that another
can be opened in its place. Hence, if a particular FILE pointer is not required after a
certain point in a program, pass it to fclose and close the file.
Syntax: fclose(filepointer);
Example: fclose(fp); // Where fp is a file pointer
Example Program1 using write mode to create new file and to write the data in file:
#include<stdio.h>
void main(){
int i;
char name[15];
FILE *fp;
fp=fopen("data1.txt","w");
printf("Input an integer");
scanf("%d",&i);
printf("Enter your name:");
scanf("%s",name);
fprintf(fp,"%d\n%s",i,name);
fclose(fp);
}
Output:
Input an intiger5
Enter ur name:gitam
Data1.txt
5
gitam
Example Program2 using read mode to read the data from file:
#include<stdio.h>
void main() {
int i;
char name[15];
FILE *fp;
fp=fopen("data1.txt","r");
fscanf(fp,"%d%s",&i,name);
printf("The integer in data1.txt is %d\n",i);
printf("The String in data1.txt is %s",name);
fclose(fp);
}
Output:
The integer in data1.txt is 5
The String in data1.txt is gitam
Example Program3 using append mode to add the data in the existing file:
#include<stdio.h>
void main() {
char name[15];
FILE *fp;
fp=fopen("data2.txt","a");
printf("Enter ur name:");
scanf("%s",name);
fprintf(fp,"%s",name);
fclose(fp);
fp=fopen("data2.txt","r");
if(fscanf(fp,"%s",name))
printf("%s",name);
fclose(fp);
}
Output:
Enter ur name:GITAM
GITAM
In data2.txt
GITAM
Again after appending:
Enter Ur name: University
GITAMUniversity
In data2.txt
GITAMUniversity
FILE STRUCTURE:
I/O functions available are similar to their console counterparts; scanf becomes fscanf, printf
becomes fprintf, etc., These functions read and write from file streams. As an example, the file
stream structure FILE defined in the header file stdio.h in DOS is shown below:
typedef struct
{
int level; /* fill/empty level of buffer */
usigned flasgs; /* File status flags */
char fd; /* File descriptor (handle) */
unsigned char hold; /* Ungetc char if no buffer */
int bsize; /* Buffer size */
unsigned char _FAR *buffer; /* Data transfer buffer */
unsigned char _FAR *curp;/* Current active pointer */
unsigned istemp; /* Temporary file indicator */
short token; /* Used for validity checking */
} FILE; /* This is the FILE Object *
NOTE: FILE is defined as New Structure Data Type in the stdio.h file as shown in above
method.
End Of File:
✔ EOF is a macro defined as an int with a negative value. It is normally returned by
functions that perform read operations to denote either an error or end of input. Input
from a terminal never really "ends" (unless the device is disconnected), but it is useful to
enter more than one "file" into a terminal, so a key sequence is reserved to indicate end of
input.
✔ Cntrl+Z is the key in DOS to end or terminate the input values.
✔ fgetc( ) or getc( ) is a predefined file handling function which is used to read a single
character from a existing file opened in read(“r”) mode by fopen( ), which is same as like
getchar( ) function.
Syntax:
ch_var= fgetc(filepointer); (Or) ch_var=getc(filepointer);
Example: char ch;
ch=fgetc(fp); (Or) ch=getc(fp);
Where ‘ch’ is a character variable to be written to the file.
Where ‘fp’ is a file pointer object.
✔ getc( ) or fgetc( ) gets the next character from the input file to which the file pointer fp
points to. The function getc( ) will return an end-of-file(EOF) marker when the end of
the file has been reached or it if encounters an error.
✔ On Success the function fputc( ) or putc( ) will return the value that it has written to the
file, otherwise it returns EOF.
Example: /* A program to Read a file */
#include<stdio.h>
main( ){
FILE *fp;
char ch;
✔ fgets( ) is a predefined file handling function which is used to read a line of text from an
existing file opened in read(“r”) mode by fopen( ), which is same as like gets( ) function.
General Format is:
char *fgets(char *s, int n,FILE *fp);
Syntax:
fgets(ch_var ,str_length, filepointer);
✔ The function fgets( ) read character from the stream fp into the character array ‘ch’ until a
newline character is read, or end-of-file is reached. It then appends the terminating null
character after the last character read and returns ‘ch’ if end-of-file occurs before reading any
character an error occurs during input fgets( ) returns NULL.
Writing Or Printing String in a file: fputs( )
✔ fputs( ) is a predefined file handling function which is used to print a string in a new file
opened in write(“w”) mode by fopen( ), which is same as like puts( ) function.
General Format:
Int fputs(const char *s, FILE *fp);
Syntax:
fputs(ch_var , filepointer);
The getw( ) and putw( ) are predefined file handling integer-oriented functions. They are
similar to the getc( ) and putc( ) functions and are used to read and write integer values.
These functions would be useful when we deal with only integer data. The general forms of
getw and putw are:
#include<stdio.h>
main()
{ int n,m;
FILE *fp=fopen("num.txt","w");
puts("Enter a number:");
scanf("%d",&n);
putw(n,fp); /* printing only integer value in a file */
fclose(fp);
fp=fopen("num.txt","r");
m=getw(fp); /* reading only integer value from a file */
printf("From File int val=%d",m);
}
Output1:
Enter a number: 16
From File int val=16
Output2:
Enter a number: 25 35 45
From File int val=25 /* here it take only one value, basing
on program requirement */
Output3:
Enter a number: 25.5
Frm File int val=25
Output4:
Enter a number: A
Frm File int val=28056 /* here it doesn’t print ASCII value of
‘A’, it just print some-garbage value */
Example: /* A program to Write and Read more Integer Values in a file */
#include<stdio.h>
main()
{ int n,m;
FILE *fp=fopen("num.txt","w");
puts(“Press Cntl+Z to end the values”);
puts("Enter the numbers:");
while(scanf("%d",&n)!=EOF)
putw(n,fp);
fclose(fp);
fp=fopen("num.txt","r");
puts(“Entered values in file are:”);
while((m=getw(fp))!=EOF)
printf("%d\n",m);
}
Output:
Press Cntl+Z to end the values
Enter the numbers:
1 2 10 20 30 45
^Z
Entered values in file are:
1
2
10
20
30
45
/* File program to read a character file and encrypts it by
replacing each alphabet by its next alphabet cyclically i.e., z
is replaced by a. Non-alphabets in the file are retained as they
are. Write the encrypted text into another file */
#include<stdio.h>
#include<stdlib.h>
main()
{
FILE *fp1,*fp2;
char fname1[20],fname2[20];
char ch1,ch2;
printf("Enter the source file name ");
scanf("%s",fname1);
fp1=fopen(fname1,"r");
if(fp1==NULL)
printf("%s is not available",fname1);
else
{
printf("Enter the new file name ");
scanf("%s",fname2);
fp2=fopen(fname2,"w");
while((ch1=fgetc(fp1))!=EOF)
{
printf("%c",ch1);
if((ch1>=65 && ch1<=89) || (ch1>=97 && ch1<=121))
ch2=ch1+1;
else if(ch1==90 || ch1==122)
ch2=ch1-25;
else
ch2=ch1;
fputc(ch2,fp2);
}
printf("File copied into %s succesfull",fname2);
fclose(fp1);
fclose(fp2);
}
}
Output:
Computer i
#include<stdio.h>
main()
{
FILE *fp;
int s=0,b=0;
char c;
fp=fopen(“fib.c”,”r”);
while((c=getc(fp))!=EOF)
{
if(c==’;’)
s++;
if(c==’{‘)
b++;
}
fclose(fp);
printf(“\t\n number of statement terminators=%d”,s);
printf(“\t\n no of opening braces=%d”,b);
}
Output :
Number of Statements terminators=10
No.of Opening braces=3
#include<stdio.h>
main()
{
FILE *fp1,*fp2;
char s;
fp1=fopen(“input.txt”,”r”);
fp2=fopen(“output.txt”,”w”);
while ((s=getc(fp1))!=EOF)
putc(s,fp2);
fclose(fp1);
fclose(fp2);
}
/*Program to append the contents to a file and display the
contents before and after appending.*/
#include<stdio.h>
#include<conio.h>
main()
{
FILE *fp1,*fp2;
char s,c;
clrscr();
printf("\n\n\t one.txt contents are \n\n");
/*prints contents of file1 on monitor*/
fp1=fopen("one.txt","r");
while((c=getc(fp1))!=EOF)
printf("%c",c);
fclose(fp1);
printf("\n\n\t two.txt contents before appending are \n\n");
/*prints contents of file2 on monitor before appending*/
fp2=fopen("two.txt","r");
while((c=getc(fp2))!=EOF)
printf("%c",c);
fclose(fp2);
/*appends contents of file1 to file2*/
fp1=fopen("one.txt","r");
fp2=fopen("two.txt","a");
while((c=getc(fp1))!=EOF)
putc(c,fp2);
fcloseall();
printf("\n\n\t two.txt contents after appending are \n\n");
/*prints contents of file2 on monitor after appending*/
fp2=fopen("two.txt","r");
while((c=getc(fp2))!=EOF)
printf("%c",c);
fclose(fp2);
}
Output:
#include<stdio.h>
#include<conio.h>
main()
{
FILE *fp,*fp1,*fp2;
int c,i;
clrscr();
fp=fopen("data.txt","w");
printf("enter the numbers");
for(i=0;i<10;i++)
{
scanf("%d",&c);
putw(c,fp);
}
fclose(fp);
fp=fopen("data.txt","r");
fp1=fopen("even.txt","w");
fp2=fopen("odd.txt","w");
while((c=getw(fp))!=EOF)
{
if(c%2==0)
putw(c,fp1);
else
putw(c,fp2);
}
fclose(fp);
fclose(fp1);
fclose(fp2);
fp1=fopen("even.txt","r");
while((c=getw(fp1))!=EOF)
printf("%4d",c);
printf("\n\n");
fp2=fopen("odd.txt","r");
while((c=getw(fp2))!=EOF)
printf("%4d",c);
fcloseall();
}
Output:
Enter the numbers 1 2 3 4 5 6 7 8 9 10
Enter the numbers 1 2 3 4 5 6 7 8 9 10
2 4 6 8 10
1 3 5 7 9