0% found this document useful (0 votes)
220 views

FILES in C Programming Language

It's all about how to use file in c programming language and full details about it in briefly manner.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
220 views

FILES in C Programming Language

It's all about how to use file in c programming language and full details about it in briefly manner.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 19

FILES

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() Creates a new file for use


Opens a new existing file for use
Ex: fp=fopen(“gitam.txt”, “w”);
fclose() Closes a file which has been opened for use
Ex: fclose(fp);
fgetc() or Reads a character from a file
getc() Ex: ch=fgetc(fp);
or ch=getc(fp);
fputc() or Writes a character to a file
putc() Ex: fputc(ch,fp);
or putc(ch,fp);
fprintf() Writes a set of data values to a file
Ex: fprintf(fp,“%d”,n);
fscanf() Reads a set of data values from a file
Ex: fscanf(fp,“%d”,&n);
getw( ) Reads only integer from a file
// Its not fgetw() Ex: n=getw(fp);
putw() Writes only integer to the file
// Its not fputw() Ex: putw(n,fp);
fgets() Reads a string from the a file
Ex: fgets(ch,sizeof(string),fp);
fputs() Writes a string to a file
Ex: fputs(ch,fp);
fseek() Sets the position to a desired point in the file
Ex: fseek(fp,0,SEEK_SET);
ftell() Gives the current position in the file
Ex: n=ftell(fp);

Opening files: fopen( )

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 will be file saved in computer?


A) If you didn’t mention the path, by default the file will be saved in TC folder, i.e., in
the drive where C-Lang is installed.
Example: fp=fopen(“hello.txt”, “w”);
B) If you mention the path in fopen( ) function, then the new file will be saved in that
particular path. Path should be mentioned as follows:
Example: fp=fopen(“d:\\gitam\\hello.txt”, “w”);
(Or)
fp=fopen(“d:/gitam/hello.txt”, “w”);

Writing to Files : fprintf( )


It is a predefined file handling function which is used to print the content in a file. The fprintf( )
function is identical to printf( ) function except that they work on files. The first argument of this
function is a file pointer which specifies the file to be used. The general form of fprintf is:

Syntax: fprintf(fp,”control string”, var_list);

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.

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


Here, name is an array variable of type char and age is an int variable
Reading from Files : fscanf( )
It is a predefined file handling function which is used to read the content from a file. The fscanf(
) function is identical to scanf( ) function except that they work on files. The first argument of
this function is a file pointer which specifies the file to be used. The general format of fscanf is:
Syntax: fscanf(fp, “controlstring”,var_list);
This statement would cause the reading of items in the control string.
Example: fscanf(fp, “%s%d”,name,&quantity”);
Where fp id is a file pointer associated with a file that has been opened for reading. The control
string is file output specifications list may include variable, constant and string.
Closing the File : fclose( fp)

⮚ 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.

✔ Cntrl+D is the key in UNIX to end or terminate the input values.


Example: /* A program to Write a file and read a file */
#include<stdio.h>
main( ){
FILE *fp;
char ch;
fp=fopen("DATA1.txt","w");
printf("Enter the Text:\n");
printf("Use Ctrl+z to stop entry \n");
while((scanf("%c",&ch))!=EOF)
fprintf(fp, “%c",ch);
fclose(fp);
printf("\n");
fp=fopen("DATA1.txt","r");
printf("Entered Text is:\n");
while((fscanf(fp,"%c",&ch))!=EOF)
printf("%c",ch);
fclose(fp);
}
Output:
Enter the Text:
Use Ctrl+z to stop entry
Hi Raju...
how r u... how is ur studies...:-)
^Z // Cntrl+Z key terminated the input
values
Entered Text is:
Hi Raju...
how r u... how is ur studies...:-)

File Handling Functions:


We having various kinds of File Handling Functions, as some of them are discussed in previous
notes and remaining we can discuss now…

Reading Character from a file: fgetc( ) or getc( )

✔ 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;

fp=fopen("DATA1.txt","r"); /* DATA1.txt is an already


existing file with content */
printf("Text from file is:\n");
while((ch=fgetc(fp))!=EOF)
/* (Or)
while((ch=getc(fp))!=EOF)*/
printf("%c",ch);
fclose(fp);
}
Output:
Text from file is:
Hi Raju... how r u... how is ur studies...:-)
Writing Or Printing Character in a file: fputc( ) or putc( )
✔ fputc( ) or putc( ) is a predefined file handling function which is used to print a single
character in a new file opened in write(“w”) mode by fopen( ), which is same as like
putchar( ) function.
Syntax:
fputc(ch_var , filepointer); (Or) putc(ch_var , filepointer);
Example: fputc(ch, fp); (Or) putc(ch, fp);
Where ‘ch’ is a character variable.
Where ‘fp’ is a file pointer object.
Example:
/* A program to Write a Character in a file and read a Character from a file */
#include<stdio.h>
main( ){
FILE *fp;
char ch;
fp=fopen("DATA1.txt","w");

printf("Enter the Text:\n");


printf("Use Ctrl+z to stop entry \n");
while((ch=getchar( ) )!=EOF) /*

fputc(ch,fp); /* (Or) putc(ch,fp); */


fclose(fp);
printf("\n");
fp=fopen("DATA1.txt","r");
printf("Entered Text is:\n");
while((ch=fgetc(fp))!=EOF)
putchar(ch);
fclose(fp);
}
Output:
Enter the Text:
Use Ctrl+z to stop entry
Hi ...
how are you... how is your studies...:-)
^Z // Cntrl+Z key terminated the input
values

Entered Text is:


Hi ...
how are you... how is your studies...:-)
Reading String from a file: fgets( )

✔ 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);

Example: char ch[10];


fgets(ch ,20, fp);
Where ‘ch’ is a string variable to be written to the file.
Where ‘fp’ is a file pointer object.
Where 20 is the string length in a file.

✔ 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);

Example: char ch[10]=”gitam”;


fputs(ch, fp);
Where ‘ch’ is a string variable.
Where ‘fp’ is a file pointer object.
The function fputs( ) writes to the stream fp except the terminating null character of string s, it
returns EOF if an error occurs during output otherwise it returns a non negative value.
Example: /* A program to Write and Read a string in a file */
#include<stdio.h>
main()
{
char name[20];
char name1[20];
FILE *fp;
fp=fopen("dream.txt","w");
puts(“Enter any String\n”);
gets(name);
fputs(name,fp);
fclose(fp);
fp=fopen("dream.txt","r");
fgets(name1,10,fp); /* Here ‘10’ is nothing but String
Length, i.e., upto how-
puts(“String from file is:\n”); many characters u want to
access from a file. */
puts(name1);
fclose(fp);
}
Output:
Enter any String:
hi ram how r u
String from file is:
hi ram ho
Reading and Printing only integer value :getw() and putw():

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:

Syntax for getw( ):


integervariable=getw(filepointer);
Example:
int n;
n= getw(fp);
Syntax for putw( ):
putw(integervariable, filepointer);
Example:
putw(n,fp);
Example: /* A program to Write and Read only one Integer Value in a file */

#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:

Enter the source file name apple.txt


Enter the new file name orange.txt
Vizag Zoo cell: 984822338File copied into orange.txt succesfull

Input text apple.txt Output text orange.txt

/*Program to read data from input file and place first 10


characters in an array and display on the monitor.*/
#include<stdio.h>
main()
{
FILE *fp;
int i=0;
char c,a[11];
fp=fopen(“INPUT”,”r”);
while(i<100)
{
c=getc(fp);
a[i]=c;
i++;
}
fclose(fp);
a[i]=’\0’;
puts(a);
}
Output

Computer i

/*Program to read a C program and count number of statement


terminators and number of opening braces.*/

#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

/*Program to copy contents of one file into another file.*/

#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:

one.txt contents are


C was developed by Denis Ritchie
two.txt contents befor appending are
C IS A MIDDLE LEVEL LANGUAGE.
two.txt contents after appending are
C IS A MIDDLE LEVEL LANGUAGE. C was developed by Denis Ritchie

/*Program to change all upper case letters in a file to lower


case letters and vice versa.*/
#include<stdio.h>
main()
{
FILE *fp1,*fp2;
char c;
fp1=fopen("text.txt","r");
fp2=fopen("copy.txt","w");
while((c=getc(fp1))!=EOF)
{
if(c>=65&&c<=91)
c=c+32;
else
c=c-32;
putc(c,fp2);
}
fcloseall();
}
/*Program to read numbers from a file “data” which contains
a series of integer numbers and then write all odd numbers
to the file to be called “odd” and all even numbers to a file
called “even”.*/

#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

You might also like