0% found this document useful (0 votes)
454 views9 pages

File Operations in C

The document discusses file handling in C programming. It describes creating, opening, closing, reading from and writing to both text and binary files using functions like fopen(), fclose(), fprintf(), fscanf(), fread(), fwrite() with examples. The different file opening modes and using structures with binary files is also explained.

Uploaded by

Adnan Al-Emran
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)
454 views9 pages

File Operations in C

The document discusses file handling in C programming. It describes creating, opening, closing, reading from and writing to both text and binary files using functions like fopen(), fclose(), fprintf(), fscanf(), fread(), fwrite() with examples. The different file opening modes and using structures with binary files is also explained.

Uploaded by

Adnan Al-Emran
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/ 9

Department of

Computer Science and Engineering

Title: File Operations in C

Structured Programming Lab


CSE 104

Green University of Bangladesh


1 Learning Objective
• To create, update, read, and delete the files stored on the local file system through C program
• To handle standard I/O in C using fprintf(), fscanf(), fread(), fwrite(), fseek() etc. with the help of
examples

2 What is File Handling in C


A file is nothing but a source of storing information permanently in the form of a sequence of bytes on a disk.
The contents of a file are not volatile like the C compiler memory. The various operations available like creating
a file, opening a file, reading a file or manipulating data inside a file is referred to as file handling.

2.1 Why files are needed


There is a time when the output generated by compiling and running the program does not serve the purpose.
If we want to check the output of the program several times, it becomes a tedious task to compile and run
the same program multiple times. This is where file handling comes into play. Here are some of the following
reasons behind the popularity of file handling:
• Reusability: It helps in preserving the data or information generated after running the program.
• Large storage capacity: Using files, we need not worry about the problem of storing data in bulk.
• Saves time: There are certain programs that require a lot of input from the user. We can easily access
any part of the code with the help of certain commands.
• Portability: We can easily transfer the contents of a file from one computer system to another without
having to worry about the loss of data.

3 Types of Files
When dealing with files, there are two types of files we should know about:
1. Text files
2. Binary files

3.1 Text files


Text files are the normal .txt files. We can easily create text files using any simple text editors such as Notepad.
When we open those files, we will see all the contents within the file as plain text. We can easily edit or delete
the contents. They take minimum effort to maintain, are easily readable, and provide the least security and
takes bigger storage space.

3.2 Binary files


Binary files are mostly the .bin files in our computer. Instead of storing data in plain text, they store it in the
binary form (0’s and 1’s). They can hold a higher amount of data, are not readable easily, and provides better
security than text files.

4 File Operations
In C, we can perform four major operations on files, either text or binary:
1. Creating a new file
2. Opening an existing file
3. Closing a file
4. Reading from and writing information to a file

1
4.1 Working with files
When working with files, you need to declare a pointer of type file. This declaration is needed for communication
between the file and the program.
1 FILE ∗ f p t r ;

4.2 Opening a file - for creation and edit


Opening a file is performed using the fopen() function defined in the stdio.h header file. The syntax for opening
a file in standard I/O is:
1 p t r = f o p e n ( " f i l e o p e n " , "mode" ) ;

For example,
1 f o p e n ( "E: \ \ cprogram \\ newprogram . t x t " , "w" ) ;
2 f o p e n ( "E: \ \ cprogram \\ oldprogram . b i n " , " rb " ) ;

Let’s suppose the file newprogram.txt doesn’t exist in the location E:\cprogram. The first function creates
a new file named newprogram.txt and opens it for writing as per the mode ’w’. The writing mode allows us
to create and edit (overwrite) the contents of the file. Now let’s suppose the second binary file oldprogram.bin
exists in the location E:\cprogram. The second function opens the existing file for reading in binary mode ’rb’.
The reading mode only allows us to read the file, we cannot write into the file.

Figure 1: Opening Modes in Standard I/O

4.3 Closing a File


The file (both text and binary) should be closed after reading/writing. Closing a file is performed using the
fclose() function.
1 fclose ( fptr ) ;

Here, fptr is a file pointer associated with the file to be closed.

4.4 Reading and writing to a text file


For reading and writing to a text file, we use the functions fprintf() and fscanf().
They are just the file versions of printf() and scanf(). The only difference is that fprintf() and fscanf()
expects a pointer to the structure FILE.

2
Example 1: Write to a text file
The following program takes a number from the user and stores in the file program.txt.
1 #i n c l u d e <s t d i o . h>
2 #i n c l u d e < s t d l i b . h>
3
4 i n t main ( )
5 {
6 i n t num ;
7 FILE ∗ f p t r ;
8
9 f p t r = f o p e n ( "C: \ \ program . t x t " , "w" ) ;
10
11 i f ( f p t r == NULL)
12 {
13 p r i n t f ( " Error ! " ) ;
14 exit (1) ;
15 }
16
17 p r i n t f ( " Enter num : " ) ;
18 s c a n f ( "%d" ,&num) ;
19
20 f p r i n t f ( f p t r , "%d" ,num) ;
21 fclose ( fptr ) ;
22
23 return 0;
24 }

After we compile and run this program, we can see a text file program.txt created in C drive of our computer.
When we open the file, we can see the integer we entered.

Example 2: Read from a text file


The following program reads the integer present in the program.txt file and prints it onto the screen. If we
successfully created the file from Example 1, running this program will get us the integer we entered. Other
functions like fgetchar(), fputc() etc. can be used in a similar way.
1 #i n c l u d e <s t d i o . h>
2 #i n c l u d e < s t d l i b . h>
3
4 i n t main ( )
5 {
6 i n t num ;
7 FILE ∗ f p t r ;
8
9 if ( ( f p t r = f o p e n ( "C: \ \ program . t x t " , " r " ) ) == NULL) {
10 p r i n t f ( " Error ! opening f i l e " ) ;
11
12 // Program e x i t s i f the f i l e p o i n t e r r e t u r n s NULL.
13 exit (1) ;
14 }
15
16 f s c a n f ( f p t r , "%d" , &num) ;
17
18 p r i n t f ( " Value o f n=%d" , num) ;
19 fclose ( fptr ) ;
20
21 return 0;
22 }

4.5 Reading and writing to a binary file


Functions fread() and fwrite() are used for reading from and writing to a file on the disk respectively in case of
binary files.

4.5.1 Writing to a binary file


To write into a binary file, we need to use the fwrite() function. The functions take four arguments:

3
1. address of data to be written in the disk
2. size of data to be written in the disk
3. number of such type of data
4. pointer to the file where we want to write.

1 f w r i t e ( addr essDat a , s i z e D a t a , numbersData , p o i n t e r T o F i l e ) ;

Example 3: Write to a binary file using fwrite()

1 #i n c l u d e <s t d i o . h>
2 #i n c l u d e < s t d l i b . h>
3
4 s t r u c t threeNum
5 {
6 i n t n1 , n2 , n3 ;
7 };
8
9 i n t main ( )
10 {
11 int n;
12 s t r u c t threeNum num ;
13 FILE ∗ f p t r ;
14
15 if ( ( f p t r = f o p e n ( "C: \ \ program . b i n " , "wb" ) ) == NULL) {
16 p r i n t f ( " Error ! opening f i l e " ) ;
17
18 // Program e x i t s i f the f i l e p o i n t e r r e t u r n s NULL.
19 exit (1) ;
20 }
21
22 f o r ( n = 1 ; n < 5 ; ++n )
23 {
24 num . n1 = n ;
25 num . n2 = 5∗n ;
26 num . n3 = 5∗n + 1 ;
27 f w r i t e (&num , s i z e o f ( s t r u c t threeNum ) , 1 , f p t r ) ;
28 }
29 fclose ( fptr ) ;
30
31 return 0;
32 }

In this program, we create a new file program.bin in the C drive. We declare a structure threeNum with three
numbers - n1, n2 and n3, and define it in the main function as num. Now, inside the for loop, we store the
value into the file using fwrite(). The first parameter takes the address of num and the second parameter takes
the size of the structure threeNum. Since we’re only inserting one instance of num, the third parameter is 1.
And, the last parameter *fptr points to the file we’re storing the data. Finally, we close the file.

4.5.2 Reading from a binary file


Function fread() also take 4 arguments similar to the fwrite() function as above.
1 f r e a d ( addr essDat a , s i z e D a t a , numbersData , p o i n t e r T o F i l e ) ;

Example 4: Read from a binary file using fread()

1 #i n c l u d e <s t d i o . h>
2 #i n c l u d e < s t d l i b . h>
3
4 s t r u c t threeNum
5 {
6 i n t n1 , n2 , n3 ;
7 };
8

4
9 i n t main ( )
10 {
11 int n;
12 s t r u c t threeNum num ;
13 FILE ∗ f p t r ;
14
15 if ( ( f p t r = f o p e n ( "C: \ \ program . b i n " , " rb " ) ) == NULL) {
16 p r i n t f ( " Error ! opening f i l e " ) ;
17
18 // Program e x i t s i f the f i l e p o i n t e r r e t u r n s NULL.
19 exit (1) ;
20 }
21
22 f o r ( n = 1 ; n < 5 ; ++n )
23 {
24 f r e a d (&num , s i z e o f ( s t r u c t threeNum ) , 1 , f p t r ) ;
25 p r i n t f ( " n1 : %d\ tn2 : %d\ tn3 : %d\n" , num . n1 , num . n2 , num . n3 ) ;
26 }
27 fclose ( fptr ) ;
28
29 return 0;
30 }

In this program, we read the same file program.bin and loop through the records one by one. In simple
terms, we read one threeNum record of threeNum size from the file pointed by *fptr into the structure num.
we shall get the same records we inserted in Example 3.

5 File handling exercises


5.1 Problem 01: C program to count characters, words and lines in a text file
Pseudocode

Algorithm 1 Character, Word and Line Counter


1: Step 01: Open source file in r (read) mode.
2: Step 02: Initialize three variables characters = 0, words = 0 and lines = 0 to store counts.
3: Step 03: Read a character from file and store it to some variable say ch.
4: Step 04: Increment characters count.
5: Step 05: Increment words count if current character is whitespace character (space, tab, new line, null
character)
6: Step 06: Increment lines count if current character is new line character i.e. if (ch == ’\n’ || ch == ’\0’).
7: Step 07: Repeat step 3-4 till file has reached end.
8: Step 08: Finally after file has reached end increment words and lines count by one if total characters > 0
to make sure we count last word and line.

Code

1 #i n c l u d e <s t d i o . h>
2 #i n c l u d e < s t d l i b . h>
3
4 i n t main ( )
5 {
6 FILE ∗ f i l e ;
7 c h a r path [ 1 0 0 ] ;
8
9 c h a r ch ;
10 i n t c h a r a c t e r s , words , l i n e s ;
11
12
13 /∗ I n p u t path o f f i l e s t o merge t o t h i r d f i l e ∗/
14 p r i n t f ( " Enter s o u r c e f i l e path : " ) ;
15 s c a n f ( "%s " , path ) ;
16
17 /∗ Open s o u r c e f i l e s i n ’ r ’ mode ∗/
18 f i l e = f o p e n ( path , " r " ) ;
19

5
20
21 /∗ Check i f f i l e opened s u c c e s s f u l l y ∗/
22 i f ( f i l e == NULL)
23 {
24 p r i n t f ( " \ nUnable t o open f i l e . \ n" ) ;
25 p r i n t f ( " P l e a s e c h e c k i f f i l e e x i s t s and you have r e a d p r i v i l e g e . \ n" ) ;
26
27 e x i t (EXIT_FAILURE) ;
28 }
29
30 /∗
31 ∗ L o g i c t o count c h a r a c t e r s , words and l i n e s .
32 ∗/
33 c h a r a c t e r s = words = l i n e s = 0 ;
34 w h i l e ( ( ch = f g e t c ( f i l e ) ) != EOF)
35 {
36 c h a r a c t e r s ++;
37
38 /∗ Check new l i n e ∗/
39 i f ( ch == ’ \n ’ | | ch == ’ \0 ’ )
40 l i n e s ++;
41
42 /∗ Check words ∗/
43 i f ( ch == ’ ’ | | ch == ’ \ t ’ | | ch == ’ \n ’ | | ch == ’ \0 ’ )
44 words++;
45 }
46
47 /∗ I n c r e m e n t words and l i n e s f o r l a s t word ∗/
48 i f ( c h a r a c t e r s > 0)
49 {
50 words++;
51 l i n e s ++;
52 }
53
54 /∗ P r i n t f i l e s t a t i s t i c s ∗/
55 p r i n t f ( " \n" ) ;
56 p r i n t f ( " Total c h a r a c t e r s = %d\n" , c h a r a c t e r s ) ;
57 p r i n t f ( " Total words = %d\n" , words ) ;
58 p r i n t f ( " Total lines = %d\n" , l i n e s ) ;
59
60
61 /∗ C l o s e f i l e s t o r e l e a s e r e s o u r c e s ∗/
62 fclose ( file ) ;
63
64 return 0;
65 }

Input
Suppose if data\file3.txt contains
I love programming.
Working with files in C programming is fun.
I am learning C programming at Bangladesh.

Output
Total characters = 106
Total words = 18
Total lines = 3

6
5.2 Problem 02: C program to count occurrences of a word in file
Pseudocode

Algorithm 2 Word Frequency Calculation


1: Step 01: Open source file in r (read) mode, store its reference to fptr.
2: Step 02: Input word to search from user, store it in word.
3: Step 03: Initialize a variable count = 0 to store total occurrences of word.
4: Step 04: Read a line from file and store it in str.
5: Step 05: Increment count by one, if an occurrence of word is found in str.
6: Step 06: Repeat step 4-5 till end of file.
7: Step 07: Finally close fptr to release all resources.

Code

1 #i n c l u d e <s t d i o . h>
2 #i n c l u d e < s t d l i b . h>
3 #i n c l u d e < s t r i n g . h>
4 #d e f i n e BUFFER_SIZE 1000
5 i n t c o u n t O c c u r r e n c e s ( FILE ∗ f p t r , c o n s t c h a r ∗ word ) ;
6
7
8 i n t main ( )
9 {
10 FILE ∗ f p t r ;
11 c h a r path [ 1 0 0 ] ;
12 c h a r word [ 5 0 ] ;
13 i n t wCount ;
14
15 /∗ I n p u t f i l e path ∗/
16 p r i n t f ( " Enter f i l e path : " ) ;
17 s c a n f ( "%s " , path ) ;
18
19 p r i n t f ( " Enter word t o s e a r c h i n f i l e : ") ;
20 s c a n f ( "%s " , word ) ;
21
22 /∗ Try t o open f i l e ∗/
23 f p t r = f o p e n ( path , " r " ) ;
24
25 /∗ E x i t i f f i l e not opened s u c c e s s f u l l y ∗/
26 i f ( f p t r == NULL)
27 {
28 p r i n t f ( " Unable t o open f i l e . \ n" ) ;
29 p r i n t f ( " P l e a s e c h e c k you have r e a d / w r i t e p r e v i l e g e s . \ n" ) ;
30
31 e x i t (EXIT_FAILURE) ;
32 }
33 wCount = c o u n t O c c u r r e n c e s ( f p t r , word ) ;
34
35 p r i n t f ( " ’% s ’ i s found %d t i m e s i n f i l e . " , word , wCount ) ;
36
37 fclose ( fptr ) ;
38
39 return 0;
40 }
41
42
43 /∗ ∗
44 ∗ Returns t o t a l o c c u r r e n c e s o f a word i n g i v e n f i l e .
45 ∗/
46 i n t c o u n t O c c u r r e n c e s ( FILE ∗ f p t r , c o n s t c h a r ∗ word )
47 {
48 c h a r s t r [ BUFFER_SIZE ] ;
49 c h a r ∗ pos ;
50
51 i n t index , count ;
52
53 count = 0 ;
54

7
55 // Read l i n e from f i l e t i l l end o f f i l e .
56 w h i l e ( ( f g e t s ( s t r , BUFFER_SIZE, f p t r ) ) != NULL)
57 {
58 index = 0 ;
59
60 // Find n e x t o c c u r r e n c e o f word i n s t r
61 w h i l e ( ( pos = s t r s t r ( s t r + index , word ) ) != NULL)
62 {
63 // Index o f word i n s t r i s
64 // Memory a d d r e s s o f pos − memory
65 // a d d r e s s o f s t r .
66 i n d e x = ( pos − s t r ) + 1 ;
67
68 count++;
69 }
70 }
71
72 r e t u r n count ;
73 }

Input
Suppose data\file3.txt contains

I love programming.
I am learning C programming at Green University.
Programming with files is fun.
Learning C programming at Green University is simple and easy.

Output
Enter file path: data/file3.txt
Enter word to search in file: Green
‘Green’ is found 2 times in file.

6 Lab Task (Please implement yourself and show the output to the
instructor)
1. Write a C program to read name and marks of n number of students and store them in a file.

2. Write a C program to write all the members of an array of structures to a file using fwrite(). Read the
array from the file and display on the screen.
3. Write a C program to find and replace a word in a text file.

7 Lab Exercise (Submit as a report)


1. Write a C program to read name and marks of n number of students from and store them in a file. If the
file previously exits, add the information to the file.
2. Write a C program to count occurrences of all words in a text file.

3. Write a C program to convert uppercase to lowercase character and vice versa in a text file.

8 Policy
Copying from internet, classmate, seniors, or from any other source is strongly prohibited. 100% marks will be
deducted if any such copying is detected.

You might also like