0% found this document useful (0 votes)
92 views10 pages

File Handling in C

File handling in C enables programs to create, read, update and delete files. It introduces functions like fopen(), fprintf(), fscanf(), fputc(), fgetc() and fclose() to open, read, write and close files. Examples demonstrate using these functions to write employee data to files and read the data back.

Uploaded by

Akashu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
92 views10 pages

File Handling in C

File handling in C enables programs to create, read, update and delete files. It introduces functions like fopen(), fprintf(), fscanf(), fputc(), fgetc() and fclose() to open, read, write and close files. Examples demonstrate using these functions to write employee data to files and read the data back.

Uploaded by

Akashu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

File Handling in C

In programming, we may require some specific input data to be generated several numbers of times. Sometimes,
it is not enough to only display the data on the console. The data to be displayed may be very large, and only a
limited amount of data can be displayed on the console, and since the memory is volatile, it is impossible to
recover the programmatically generated data again and again. However, if we need to do so, we may store it onto
the local file system which is volatile and can be accessed every time. Here, comes the need of 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.

o Creation of the new file


o Opening an existing file
o Reading from the file
o Writing to the file
o Deleting the file

Functions for file handling


There are many functions in the C library to open, read, write, search and close the file. A list of file functions are
given below:

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


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.

We can use one of the following modes in the fopen() function.

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

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

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, ...])

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

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, ...])

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

C File Example: Storing employee information


Let's see a file handling example to store employee information as entered by user from console. We are going to
store id, name and salary of the employee.

1. #include <stdio.h>
2. void main()
3. {
4. FILE *fptr;
5. int id;
6. char name[30];
7. float salary;
8. fptr = fopen("emp.txt", "w+");/* open for writing */
9. if (fptr == NULL)
10. {
11. printf("File does not exists \n");
12. return;
13. }
14. printf("Enter the id\n");
15. scanf("%d", &id);
16. fprintf(fptr, "Id= %d\n", id);
17. printf("Enter the name \n");
18. scanf("%s", name);
19. fprintf(fptr, "Name= %s\n", name);
20. printf("Enter the salary\n");
21. scanf("%f", &salary);
22. fprintf(fptr, "Salary= %.2f\n", salary);
23. fclose(fptr);
24. }

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

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

C fputs() and fgets()


The fputs() and fgets() in C programming are used to write and read string from stream. Let's see examples of
writing and reading file using fgets() and fgets() functions.

Writing File : fputs() function


The fputs() function writes a line of characters into file. It outputs string to a stream.

Syntax:

1. int fputs(const char *s, FILE *stream)

Example:

1. #include<stdio.h>
2. #include<conio.h>
3. void main(){
4. FILE *fp;
5. clrscr();
6.
7. fp=fopen("myfile2.txt","w");
8. fputs("hello c programming",fp);
9.
10. fclose(fp);
11. getch();
12. }
Reading File : fgets() function
The fgets() function reads a line of characters from file. It gets string from a stream.

Syntax:

1. char* fgets(char *s, int n, FILE *stream)

Example:

1. #include<stdio.h>
2. #include<conio.h>
3. void main(){
4. FILE *fp;
5. char text[300];
6. clrscr();
7.
8. fp=fopen("myfile2.txt","r");
9. printf("%s",fgets(text,200,fp));
10.
11. fclose(fp);
12. getch();
13. }

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 example", fp);
7.
8. fseek( fp, 7, SEEK_SET );
9. fputs("by student", fp);
10. fclose(fp);
11. }

C rewind() function
The rewind() function sets the file pointer at the beginning of the stream. It is useful if you have to use stream
many times.

Syntax:

1. void rewind(FILE *stream)

1. #include<stdio.h>
2. #include<conio.h>
3. void main(){
4. FILE *fp;
5. char c;
6. clrscr();
7. fp=fopen("file.txt","r");
8.
9. while((c=fgetc(fp))!=EOF){
10. printf("%c",c);
11. }
12.
13. rewind(fp);//moves the file pointer at beginning of the file
14.
15. while((c=fgetc(fp))!=EOF){
16. printf("%c",c);
17. }
18.
19. fclose(fp);
20. getch();
21. }
C ftell() function
The ftell() function returns the current file position of the specified stream. We can use ftell() function to get the
total size of a file after moving file pointer at the end of file. We can use SEEK_END constant to move the file
pointer at the end of file.

Syntax:

1. long int ftell(FILE *stream)

1. #include <stdio.h>
2. #include <conio.h>
3. void main (){
4. FILE *fp;
5. int length;
6. clrscr();
7. fp = fopen("file.txt", "r");
8. fseek(fp, 0, SEEK_END);
9.
10. length = ftell(fp);
11.
12. fclose(fp);
13. printf("Size of file: %d bytes", length);
14. getch();
15. }

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.

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

1. #include <stdio.h>
2. void main(int argc, char *argv[] ) {
3.
4. printf("Program name is: %s\n", argv[0]);
5.
6. if(argc < 2){
7. printf("No argument passed through command line.\n");
8. }
9. else{
10. printf("First argument is: %s\n", argv[1]);
11. }
12. }

To run program

1. program.exe hello

You might also like