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

Intro To Programming Week 9

The document is a course outline for BCSC 1102: Intro to Programming, focusing on file handling in C programming. It covers types of files, file operations such as opening, reading, writing, and closing files, as well as error handling and binary file operations. A sample program for managing student records is also included to illustrate practical applications of file handling concepts.
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)
0 views

Intro To Programming Week 9

The document is a course outline for BCSC 1102: Intro to Programming, focusing on file handling in C programming. It covers types of files, file operations such as opening, reading, writing, and closing files, as well as error handling and binary file operations. A sample program for managing student records is also included to illustrate practical applications of file handling concepts.
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/ 11

BCSC 1102 : Intro To Programming Week 9

Dr. Shem Mbandu Angolo, PhD

The Co-operatetive University of Kenya


September - December 2024

Contents
1 Introduction to File Handling 2
1.1 Types of Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
1.2 File Handling Functions . . . . . . . . . . . . . . . . . . . . . . . 2

2 File Operations: Opening, Reading, Writing, Closing Files 2


2.1 Opening a File . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
2.2 Reading from a File . . . . . . . . . . . . . . . . . . . . . . . . . 3
2.3 Writing to a File . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
2.4 Closing a File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5

3 File Pointers and Error Handling 5


3.1 File Pointers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
3.2 Error Handling . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6

4 Binary File Handling 7


4.1 Writing to a Binary File . . . . . . . . . . . . . . . . . . . . . . . 7
4.2 Reading from a Binary File . . . . . . . . . . . . . . . . . . . . . 7

5 Sample Program: Managing Student Records 8

6 Conclusion 10

1
1 Introduction to File Handling
File handling is an essential part of programming that allows programs to read
data from files and write data to files. Files are used to store data permanently,
making it possible to retain information even after the program terminates.

1.1 Types of Files


There are two main types of files in C:
• Text Files: Store data in a readable format using characters.
• Binary Files: Store data in a binary format, which is not directly read-
able by humans.

1.2 File Handling Functions


C provides several functions for file handling, such as:

• fopen(): Opens a file.


• fclose(): Closes a file.
• fread(): Reads data from a file.
• fwrite(): Writes data to a file.

• fgetc(): Reads a character from a file.


• fputc(): Writes a character to a file.
• fgets(): Reads a string from a file.
• fputs(): Writes a string to a file.

2 File Operations: Opening, Reading, Writing,


Closing Files
2.1 Opening a File
To open a file, use the fopen() function, which returns a file pointer.
1 # include < stdio .h >
2

3 int main () {
4 FILE * file ;
5 file = fopen (" example . txt " , " r ") ;
6 if ( file == NULL ) {
7 printf (" Error opening file .\ n ") ;

2
8 return 1;
9 }
10 // Perform file operations
11 fclose ( file ) ;
12 return 0;
13 }

2.2 Reading from a File


To read data from a file, use functions such as fgetc(), fgets(), or fread().
1 # include < stdio .h >
2

3 int main () {
4 FILE * file ;
5 char ch ;
6

7 file = fopen (" example . txt " , " r ") ;


8 if ( file == NULL ) {
9 printf (" Error opening file .\ n ") ;
10 return 1;
11 }
12

13 // Reading characters from a file


14 while (( ch = fgetc ( file ) ) != EOF ) {
15 putchar ( ch ) ;
16 }
17

18 fclose ( file ) ;
19 return 0;
20 }

1 # include < stdio .h >


2

3 int main () {
4 FILE * file ;
5 char buffer [100];
6

7 file = fopen (" example . txt " , " r ") ;


8 if ( file == NULL ) {
9 printf (" Error opening file .\ n ") ;
10 return 1;
11 }
12

13 // Reading a string from a file

3
14 while ( fgets ( buffer , 100 , file ) != NULL ) {
15 printf ("% s " , buffer ) ;
16 }
17

18 fclose ( file ) ;
19 return 0;
20 }

2.3 Writing to a File


To write data to a file, use functions such as fputc(), fputs(), or fwrite().
1 # include < stdio .h >
2

3 int main () {
4 FILE * file ;
5 char ch = ’A ’;
6

7 file = fopen (" example . txt " , " w ") ;


8 if ( file == NULL ) {
9 printf (" Error opening file .\ n ") ;
10 return 1;
11 }
12

13 // Writing characters to a file


14 fputc ( ch , file ) ;
15

16 fclose ( file ) ;
17 return 0;
18 }

1 # include < stdio .h >


2

3 int main () {
4 FILE * file ;
5 char buffer [] = " Hello , World !";
6

7 file = fopen (" example . txt " , " w ") ;


8 if ( file == NULL ) {
9 printf (" Error opening file .\ n ") ;
10 return 1;
11 }
12

13 // Writing a string to a file


14 fputs ( buffer , file ) ;

4
15

16 fclose ( file ) ;
17 return 0;
18 }

2.4 Closing a File


To close a file, use the fclose() function.
1 # include < stdio .h >
2

3 int main () {
4 FILE * file ;
5 file = fopen (" example . txt " , " r ") ;
6 if ( file == NULL ) {
7 printf (" Error opening file .\ n ") ;
8 return 1;
9 }
10

11 // Perform file operations


12

13 fclose ( file ) ; // Closing the file


14 return 0;
15 }

3 File Pointers and Error Handling


3.1 File Pointers
A file pointer is a pointer to a structure of type FILE. It is used to keep track
of the file being accessed.
1 # include < stdio .h >
2

3 int main () {
4 FILE * file ;
5 file = fopen (" example . txt " , " r ") ;
6 if ( file == NULL ) {
7 printf (" Error opening file .\ n ") ;
8 return 1;
9 }
10

11 // Perform file operations


12

13 fclose ( file ) ;

5
14 return 0;
15 }

3.2 Error Handling


Error handling is important to ensure that the program can handle situa-
tions where file operations fail. Common functions for error handling include
ferror(), perror(), and checking the return value of file operations.
1 # include < stdio .h >
2

3 int main () {
4 FILE * file ;
5 file = fopen (" example . txt " , " r ") ;
6 if ( file == NULL ) {
7 perror (" Error opening file ") ;
8 return 1;
9 }
10

11 // Perform file operations


12 if ( ferror ( file ) ) {
13 printf (" Error reading from file .\ n ") ;
14 }
15

16 fclose ( file ) ;
17 return 0;
18 }

1 # include < stdio .h >


2

3 int main () {
4 FILE * file ;
5 file = fopen (" example . txt " , " w ") ;
6 if ( file == NULL ) {
7 perror (" Error opening file ") ;
8 return 1;
9 }
10

11 if ( fputs (" Hello , World !" , file ) == EOF ) {


12 perror (" Error writing to file ") ;
13 }
14

15 fclose ( file ) ;
16 return 0;
17 }

6
4 Binary File Handling
Binary files store data in a binary format, which is not directly readable by
humans. Binary file operations use the same functions as text file operations
but handle data differently.

4.1 Writing to a Binary File


To write data to a binary file, use the fwrite() function.
1 # include < stdio .h >
2

3 int main () {
4 FILE * file ;
5 int data = 12345;
6

7 file = fopen (" example . bin " , " wb ") ;


8 if ( file == NULL ) {
9 printf (" Error opening file .\ n ") ;
10 return 1;
11 }
12

13 // Writing data to a binary file


14 fwrite (& data , sizeof ( int ) , 1 , file ) ;
15

16 fclose ( file ) ;
17 return 0;
18 }

4.2 Reading from a Binary File


To read data from a binary file, use the fread() function.
1 # include < stdio .h >
2

3 int main () {
4 FILE * file ;
5 int data ;
6

7 file = fopen (" example . bin " , " rb ") ;


8 if ( file == NULL ) {
9 printf (" Error opening file .\ n ") ;
10 return 1;
11 }
12

13 // Reading data from a binary file

7
14 fread (& data , sizeof ( int ) , 1 , file ) ;
15 printf (" Data read from file : % d \ n " , data ) ;
16

17 fclose ( file ) ;
18 return 0;
19 }

5 Sample Program: Managing Student Records


This sample program uses a menu system to manage student records. It demon-
strates the use of structures, functions, arrays, and pointers.
1 // Headers and constants
2 # include < stdio .h >
3 # include < string .h >
4 # include < stdlib .h >
5

6 # define MAX_STUDENTS 100


7

8 // Global array of students ( data section )


9 struct Student {
10 int id ;
11 char name [50];
12 int age ;
13 };
14

15 // Array of students ( data section )


16 struct Student students [ MAX_STUDENTS ];
17 // Student count ( data section )
18 int student_count = 0;
19

20 // Function to add a student ( stack )


21 void addStudent () {
22 if ( student_count < MAX_STUDENTS ) {
23 struct Student newStudent ; // Local variable (
stack )
24 printf (" Enter ID : ") ;
25 scanf ("% d " , & newStudent . id ) ;
26 printf (" Enter name : ") ;
27 getchar () ; // To consume newline character
left by previous input
28 fgets ( newStudent . name , sizeof ( newStudent . name )
, stdin ) ;
29 newStudent . name [ strcspn ( newStudent . name , "\ n ")
] = ’\0 ’; // Remove newline character

8
30 printf (" Enter age : ") ;
31 scanf ("% d " , & newStudent . age ) ;
32

33 students [ student_count ] = newStudent ;


34 student_count ++;
35 printf (" Student added successfully !\ n ") ;
36 } else {
37 printf (" Student list is full !\ n ") ;
38 }
39 }
40

41 // Function to delete a student ( stack )


42 void deleteStudent () {
43 if ( student_count == 0) {
44 printf (" No students to delete .\ n ") ;
45 } else {
46 int id ; // Local variable ( stack )
47 printf (" Enter the ID of the student to delete :
") ;
48 scanf ("% d " , & id ) ;
49 int found = 0; // Local variable ( stack )
50 for ( int i = 0; i < student_count ; i ++) {
51 if ( students [ i ]. id == id ) {
52 found = 1;
53 for ( int j = i ; j < student_count - 1;
j ++) {
54 students [ j ] = students [ j + 1];
55 }
56 student_count - -;
57 printf (" Student deleted successfully !\
n ") ;
58 break ;
59 }
60 }
61 if (! found ) {
62 printf (" Student with ID % d not found .\ n " ,
id ) ;
63 }
64 }
65 }
66

67 // Function to print students ( stack )


68 void printStudents () {
69 if ( student_count == 0) {
70 printf (" No students to display .\ n ") ;
71 } else {

9
72 for ( int i = 0; i < student_count ; i ++) {
73 printf (" ID : % d \ n " , students [ i ]. id ) ;
74 printf (" Name : % s \ n " , students [ i ]. name ) ;
75 printf (" Age : % d \ n \ n " , students [ i ]. age ) ;
76 }
77 }
78 }
79

80 // Main function ( stack and heap )


81 int main () {
82 int choice ; // Local variable ( stack )
83 while (1) {
84 printf ("\ nStudent Records Menu :\ n ") ;
85 printf ("1. Add a student \ n ") ;
86 printf ("2. Delete a student \ n ") ;
87 printf ("3. Print the list of students \ n ") ;
88 printf ("4. Exit \ n ") ;
89 printf (" Enter your choice : ") ;
90 scanf ("% d " , & choice ) ;
91

92 switch ( choice ) {
93 case 1:
94 addStudent () ;
95 break ;
96 case 2:
97 deleteStudent () ;
98 break ;
99 case 3:
100 printStudents () ;
101 break ;
102 case 4:
103 exit (0) ;
104 default :
105 printf (" Invalid choice . Please try
again .\ n ") ;
106 }
107 }
108 return 0;
109 }

6 Conclusion
File handling in C is an essential skill for managing data storage and retrieval.
Understanding how to open, read, write, and close files, as well as handle errors,

10
is crucial for writing robust programs. Additionally, managing binary files and
implementing a menu-driven program for student records demonstrates practical
applications of these concepts.

11

You might also like