Most of the programs we have seen so far involve static or dynamic memory. One of the features of C programming language is the ability to read and write files.
The information is written to operating system files in binary format and later retrieved in the memory buffer to be read or written. This is done with the help of file pointers and various C library functions.
Learn the basics of C programming before you begin.
File Operations in C
C language allows following file operations in broader sense.
- Create new file.
- Open existing file.
- Read from a file.
- Write to a file.
- Move to a specific location on file (seek).
- Close the File.
The library functions for file operations is stored in
See the following example,
Example Program – File Operations
"test.txt"
A Square has 4 equal sides, and a rectangle has 4 sides, but they are not equal.
The triangle has 3 angles and 3 sides.
We now write a program that will use –
"Read_file.c"
#include <stdio.h>
int main()
{
FILE *file_pointer;
char ch;
/* use library function fopen() to open and existing file */
file_pointer = fopen ("test.c", "r");
while(1)
{
/* read each character from file_pointer which is pointing to file - test.c */
ch = fgetc(file_pointer);
/* EOF is a macro that signals end-of-file */
if(ch == EOF)
break;
printf("%c", ch);
}
/* All the character has been read, close the file with library function - fclose() */
fclose(file_pointer);
return 0;
}
Output:
FILE
It is a file control structure that store information about
typedef struct {
short level;
unsigned flags;
char fd;
unsigned char hold;
short bsize;
unsigned char *buffer,*curp;
unsigned istemp;
short token;
} FILE;
This is hidden from the programmer. The command
FILE *file_pointer;
creates a pointer of type
file_pointer = fopen("test.txt", "r");
fopen()
The function
- file name
- opening mode
In the example above, the file name is
What does fopen() do ?
It does three tasks.
- Search for the file on the disk.
- If found, load the file in memory buffer.
- Set a character pointer that points to the first character of the file in buffer.
Since too many disk operations is costly for operating systems. A buffer is needed so that all operations are performed in the buffer and later committed to the file on the disk.
fgetc()
The file in open in buffer and ready for file operations. The
The function
ch = fgetc(file_pointer);
fclose()
Once the
fclose(file_pointer);
Any further operation required; you have to open the file again using