Skip to content

Latest commit

 

History

History

chapter10

Chapter 10 - File Handling in C language

The Random Access Memory is a volatile memory and it's content is lost once the program terminates. In order to persist the data forever we use files.

A file is data stored in a storage device.
A C program can talk to the file by reading content from it and writing content to it.

File Pointer

The "File" is a structure which needs to be created for opening the file.
A file pointer is a pointer to this structure of the file.

File pointer is needed for communication between the file and the program.
Syntax:---
File *ptr;
ptr = fopen("filename.ext","mode");

File opening modes in C

C offers the programmers to select a mode for opening a file.

"r"Open for readingIf the file does't exist,fopen returns null
"rb"Open for reading in binaryIf the file does't exist,fopen returns null
"w"Open for writingIf the file exist the content will be over write
"wb"Open for writing in binaryIf the file exist the content will be over write
"a"Open for appendIf the file does't exist,it will be created

There are two types of files

  1. Text files.(.txt, .c)
  2. Binary files.(.jpg, .dat)

Reading Files

A file can be opened for reading as follows:

FILE *ptr;
ptr = fopen("Exam.txt","r");
int num;

We can read an integer from the file uisng

fscanf(ptr,"%d",&num);

Closing the file

It's very important to close the file after read or write.

fclose(ptr);

Writing to a file

FILE *ptr;
ptr = fopen("write.txt","w");
fprintf(ptr,"%d",num);

fgetc() and fputc()

fgetc and fputc are used to read and write a character from / to a file.

fgetc(ptr)   // -- used to read a character from file
fputc('c',ptr); // --- used to write character 'c' to the file

EOF : End of File

fgetc() returns EOF when all the characters from a file have been read. So we can write a check like below to detect end of file.

while (1)
    {
        ch = fgetc(ptr);
        if (ch == EOF)
        {
            break;
        }
        // code
    }

Exercises

  1. Write a prorgam to read three integers from a file.
  2. Write a program to generate multiplication table of a given number in text format.Make sure that the file is readable and well formatted.
  3. Write a program to read a text file character by character and write its content twice. in a seperate file.
  4. Take name and salery of two employees as input from the user and write them to a text file in the following format.
    name1,3300
    name2,7700
  5. Write a program to modify a fille containing an integer to double its value.