2. File Handling in C:
File handling in C enables us to create, update, read,
and delete the files stored on the local file system
through our C program. The following operations can
be performed on a file.
1. Creation of the new file
2. Opening an existing file
3. Reading from the file
4. Writing to the file
5. Deleting the file
3. Functions for file handling:
No. Function Description
1 fopen() opens new or existing file
2 fprintf() write data into the file
3 fscanf() reads data from the file
4 fputc() writes a character into the file
5 fgetc() reads a character from file
6 fclose() closes the file
7 fseek() sets the file pointer to given position
8 fputw() writes an integer to file
9 fgetw() reads an integer from file
10 ftell() returns current position
11 rewind() sets the file pointer to the beginning of
the file
4. Opening File: fopen()
We must open a file before it can be read, write, or update. The fopen() function is used to
open a file. The syntax of the fopen() is given below.
1. FILE *fopen( const char * filename, const char * mode );
The fopen() function accepts two parameters:
o The file name (string). If the file is stored at some specific location, then we must
mention the path at which the file is stored. For example, a file name can be
like "c://some_folder/some_file.ext".
o The mode in which the file is to be opened. It is a string.
5. Mode Description
R opens a text file in read mode
W opens a text file in write mode
A opens a text file in append mode
r+ opens a text file in read and write mode
w+ opens a text file in read and write mode
a+ opens a text file in read and write mode
Rb opens a binary file in read mode
Wb opens a binary file in write mode
Ab opens a binary file in append mode
rb+ opens a binary file in read and write mode
wb+ opens a binary file in read and write mode
ab+ opens a binary file in read and write mode
6. Consider the following example which opens a file in write mode.
1. #include<stdio.h>
2. void main( )
3. {
4. FILE *fp ;
5. char ch ;
6. fp = fopen("file_handle.c","r") ;
7. while ( 1 )
8. {
9. ch = fgetc ( fp ) ;
10. if ( ch == EOF )
11. break ;
12. printf("%c",ch) ;
13. }
14. fclose (fp ) ;
15. }
Output
The content of the file will be printed.
#include;
void main( )
{
FILE *fp; // file pointer
char ch;
fp = fopen("file_handle.c","r");
while ( 1 )
{
ch = fgetc ( fp ); //Each character of the file is read and stored in the
character file.
if ( ch == EOF )
break;
printf("%c",ch);
}
fclose (fp );
}
7. Closing File: fclose()
The fclose() function is used to close a file. The file
must be closed after performing all the operations on
it. The syntax of fclose() function is given below:
int fclose( FILE *fp );
8. C fprintf() and fscanf()
Writing File : fprintf() function
The fprintf() function is used to write set of characters into file. It sends formatted output to
a stream.
Syntax:
1. int fprintf(FILE *stream, const char *format [, argument, ...])
Example:
1. #include <stdio.h>
2. main(){
3. FILE *fp;
4. fp = fopen("file.txt", "w");//opening file
5. fprintf(fp, "Hello file by fprintf...n");//writing data into file
6. fclose(fp);//closing file
7. }
9. Reading File : fscanf() function
The fscanf() function is used to read set of characters from file. It reads a word from the file
and returns EOF at the end of file.
Syntax:
1. int fscanf(FILE *stream, const char *format [, argument, ...])
Example:
1. #include <stdio.h>
2. main(){
3. FILE *fp;
4. char buff[255];//creating char array to store data of file
5. fp = fopen("file.txt", "r");
6. while(fscanf(fp, "%s", buff)!=EOF){
7. printf("%s ", buff );
8. }
9. fclose(fp);
10. }
Output:
Hello file by fprintf...
10. C fputc() and fgetc()
Writing File : fputc() function
The fputc() function is used to write a single character into file. It outputs a character to a
stream.
Syntax:
1. int fputc(int c, FILE *stream)
Example:
1. #include <stdio.h>
2. main(){
3. FILE *fp;
4. fp = fopen("file1.txt", "w");//opening file
5. fputc('a',fp);//writing single character into file
6. fclose(fp);//closing file
7. }
file1.txt
a
11. Reading File : fgetc() function
The fgetc() function returns a single character from the file. It gets a character from the
stream. It returns EOF at the end of file.
Syntax:
1. int fgetc(FILE *stream)
Example:
1. #include<stdio.h>
2. #include<conio.h>
3. void main(){
4. FILE *fp;
5. char c;
6. clrscr();
7. fp=fopen("myfile.txt","r");
8.
9. while((c=fgetc(fp))!=EOF){
10. printf("%c",c);
11. }
12. fclose(fp);
13. getch();
14. }
myfile.txt
this is simple text message
12. C fseek() function
The fseek() function is used to set the file pointer to the specified offset. It is used to write
data into file at desired location.
Syntax:
1. int fseek(FILE *stream, long int offset, int whence)
There are 3 constants used in the fseek() function for whence: SEEK_SET, SEEK_CUR and
SEEK_END.
Example:
1. #include <stdio.h>
2. void main(){
3. FILE *fp;
4.
5. fp = fopen("myfile.txt","w+");
6. fputs("This is javatpoint", fp);
7.
8. fseek( fp, 7, SEEK_SET );
9. fputs("sonoo jaiswal", fp);
10. fclose(fp);
11. }
myfile.txt
This is sonoo jaiswal
13. Random Access To File:
There is no need to read each record sequentially, if
we want to access a particular record.C supports
these functions for random access file processing.
1. fseek()
2. ftell()
3. rewind()
14. fseek():
Thisfunction isused for seekingthepointer position in thefileat thespecified byte.
Syntax: fseek( filepointer,displacement, pointer position);
Where
file pointer ---- It isthepointer which pointsto thefile.
displacement ---- It ispositiveor negative.Thisisthenumber of byteswhich areskipped backward (if
negative) or forward( if positive) from thecurrent position.Thisisattached with Lbecausethisisalong
integer.
Pointer position:
Thissetsthepointer position in thefile.
Value pointer position
0 Beginning of file.
1 Current position
2 End of file
15. Example:
1) fseek( p,10L,0)
0 means pointer position is on beginning of the file,from this
statement pointer position is skipped 10 bytes from the
beginning of the file.
2)fseek( p,5L,1)
1 means current position of the pointer position.From this
statement pointer position is skipped 5 bytes forward from
the current position.
3)fseek(p,-5L,1)
From this statement pointer position is skipped 5 bytes
backward from the current position.
16. ftell():
This function returns the value of the current pointer
position in the file.The value is count from the
beginning of the file.
Syntax: ftell(fptr);
Where fptr is a file pointer.
rewind():
This function is used to move the file pointer to the
beginning of the given file.
Syntax: rewind( fptr);
Where fptr is a file pointer.
17. Binary files:
Binary files are very similar to arrays of structures, except
the structures are in a disk file rather than in an array in
memory. Because the structures in a binary file are on disk,
you can create very large collections of them (limited only
by your available disk space). They are also permanent
and always available. The only disadvantage is the
slowness that comes from disk access time.
Binary files have two features that distinguish them from
text files:
You can jump instantly to any structure in the file, which
provides random access as in an array.
You can change the contents of a structure anywhere in
the file at any time.
Binary files also usually have faster read and write times
than text files, because a binary image of the record is
stored directly from memory to disk (or vice versa). In a text
file, everything has to be converted back and forth to text,
and this takes time.
18. Command Line Arguments in C
The arguments passed from command line are
called command line arguments. These arguments
are handled by main() function.
To support command line argument, you need to
change the structure of main() function as given
below.
int main(int argc, char *argv[] )
Here, argc counts the number of arguments. It
counts the file name as the first argument.
The argv[] contains the total number of arguments.
The first argument is the file name always.
19. Example
Let's see the example of command line arguments where we are passing one argument with
file name.
1. #include <stdio.h>
2. void main(int argc, char *argv[] ) {
3.
4. printf("Program name is: %sn", argv[0]);
5.
6. if(argc < 2){
7. printf("No argument passed through command line.n");
8. }
9. else{
10. printf("First argument is: %sn", argv[1]);
11. }
12. }
1. program.exe hello
Output:
Program name is: program
First argument is: hello
20. Run the program as follows in Windows from command line:
1. program.exe hello
Output:
Program name is: program
First argument is: hello
If you pass many arguments, it will print only one.
1. ./program hello c how r u
Output:
Program name is: program
First argument is: hello
But if you pass many arguments within double quote, all arguments will be treated as a
single argument only.
1. ./program "hello c how r u"
Output:
Program name is: program
First argument is: hello c how r u
You can write your program to print all the arguments. In this program, we are printing only
argv[1], that is why it is printing only one argument.