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.
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.
Syntax:---
File *ptr; ptr = fopen("filename.ext","mode");
C offers the programmers to select a mode for opening a file.
"r" | Open for reading | If the file does't exist,fopen returns null |
"rb" | Open for reading in binary | If the file does't exist,fopen returns null |
"w" | Open for writing | If the file exist the content will be over write |
"wb" | Open for writing in binary | If the file exist the content will be over write |
"a" | Open for append | If the file does't exist,it will be created |
- Text files.(.txt, .c)
- Binary files.(.jpg, .dat)
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);
It's very important to close the file after read or write.
fclose(ptr);
FILE *ptr; ptr = fopen("write.txt","w"); fprintf(ptr,"%d",num);
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
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 }
- Write a prorgam to read three integers from a file.
- Write a program to generate multiplication table of a given number in text format.Make sure that the file is readable and well formatted.
- Write a program to read a text file character by character and write its content twice. in a seperate file.
- 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 - Write a program to modify a fille containing an integer to double its value.