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

C File Handling

Uploaded by

subhendujena2002
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

C File Handling

Uploaded by

subhendujena2002
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

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.

The difference between the file I/O and console I/O(screen and
keyboard pair) are as below:

1. The console always exists, a particular file may or may not


exist.
2. In case of a console, the program reads from the keyboard
and writes onto the screen.
3. In case of files, it is possible (and often required, say for
an editor) to read from and write to the same file.

File I/O is always done in a program in the following sequence:

• Open the file


• Read or write to the file
• Close the file

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.

Before performing any file I/O, the file must be opened. While
opening the file, the following are specified:

• The name of the file


• The manner in which it should be opened(i.e., for reading
and writing, appending at the end of the file, overwriting
the file, etc.)

FILE *fp;

fp=fopen(“outfile1.txt”, “w”);

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

The fopen() function works in the following way.

o Firstly, it searches the file to be opened.


o Then, it loads the file from the disk and place it into the
buffer. The buffer is used to provide efficiency for the read
operations.
o It sets up a character pointer which points to the first
character of the file.

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

1. int fclose( FILE *fp );


# include<stdio.h>
void main()
{

int i;

FILE* fp=fopen(“outfile1.txt”, “w”);

printf(“Input an integer: “);

scanf(“%d”, &i);

fprintf(fp,”%d\n”,i);

fclose(fp);

}
C fprintf() and fscanf()

C fputc() and fgetc()

C fputs() and fgets()

C fseek()

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 f
ile
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.

Backward Skip 10sPlay VideoForward Skip 10s

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

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

Output:
Enter the id
1
Enter the name
sonoo
Enter the salary
120000
Now open file from current directory. For windows operating
system, go to TC\bin directory, you will see emp.txt file. It will
have following information.

emp.txt
Id= 1
Name= sonoo
Salary= 120000
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
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
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. }

myfile2.txt
hello c programming

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

Output:
hello c programming
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 C File Handling", fp);
7.
8. fseek( fp, 7, SEEK_SET );
9. fputs("sonoo jaiswal", fp);
10. fclose(fp);
11. }

myfile.txt
This is sonoo jaiswal
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)

Example:

File: file.txt

1. this is a simple text

File: rewind.c

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 t
he file
14.
15. while((c=fgetc(fp))!=EOF){
16. printf("%c",c);
17. }
18.
19. fclose(fp);
20. getch();
21. }

Output:
this is a simple text this is a simple text

As you can see, rewind() function moves the file pointer at


beginning of the file that is why "this is simple text" is printed
2 times. If you don't call rewind() function, "this is simple text"
will be printed only once.

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)

Example:

File: ftell.c

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

Output:
Size of file: 21 bytes

Explanation:

Using fseek(fp, 0, SEEK_END), the program accesses the


file "file.txt" in read mode and advances the file pointer to the
end. Using ftell(fp), it obtains the file location, which represents
the file size. Finally, the program uses the printf() function to
output the file's size in bytes. The result shows that "file.txt" has 21
bytes in it. You should take note of the program's use of uncommon
functions like clrscr() and getch().
Knowing the file's position and size is crucial for various tasks when
working with files in C programming. As the preceding example
shows, the ftell() function is essential in giving this information.
Let's look more closely at some additional crucial file operations and
ideas since file management encompasses more than simply
determining the file size.

Modes for Opening Files: In the example, we opened the file


in "r" mode. This mode indicates read-only access. Additional
access modes are available, including "w" for writing (creates a
new file or overwrites an existing one), "a" for append (writes at
the end of the file), "rb" for binary read, "wb" for binary write, etc.
It is essential to comprehend and use the proper file modes to
guarantee that the correct file actions are carried out.

Error Handling: It's critical to manage potential failures when


working with file operations properly. If the fopen()
method cannot open the file, it returns NULL. Therefore,
looking at the return value and responding appropriately is
crucial if the file opening doesn't succeed. Error
management helps you find and fix possible problems and
prevent program crashes.

File Reading and Writing: Although the function ftell() is


generally used to determine the size of a file, file handling
frequently includes reading data from and writing data to
files. For these uses, C has several methods, including fread(),
fwrite(), fgets(), and fputs(). You may efficiently modify the
content of files by becoming familiar with and using these
functions.

File Seeking: The fseek() function is used in conjunction


with ftell() to adjust the file position indication to a particular
point inside the file. It is helpful when you want to read or write
data from a specific location in the file. You can traverse a file
and perform the necessary operations with the fseek()
function.

Text vs. Binary Mode: Both binary mode and text mode are
available for opening files. While text mode is used for text
files, binary mode is appropriate for non-text files. Different
platforms (such as Windows and Unix-like systems) may treat
newline characters differently when opening a file in text mode.
In binary mode, there are no such transformations and data
is read, and written just as it is.

Conclusion:
In conclusion, the C ftell() method is a helpful resource for
locating the current file location and retrieving the file size.
Programmers may easily search through files and do actions by
combining them with the fseek() function. Successful file
handling in C depends on the understanding and use of
file opening modes, error management, and many file-
related functions. Furthermore, understanding the differences
between binary and text modes guarantees precise data
handling. C programmers who are skilled in file handling can
read, write, and modify files efficiently, enabling the creation of
various programs with exact file operations.

You might also like