File in C programming language, can be anything from a disk file to a device. C language provide support for opening a file, closing a file, reading data from a file and writing data to a file through a set of standard library functions.
C file handling is designed to work with a number of devices and file formats like printer, screen, keyboard, disk file etc. C file system transforms different devices into a abstract logical device called stream. All streams behaves same irrespective of devices and files. It provides an abstract consistent interface for C program to interact by hiding the details of the device specific implementations.
Disk file read function can be used to read data from keyboard as well.
- A Stream is a the sequence of bytes of data.
- All Streams behaves similarly. Same code can be used to perform I/O operations of various streams.
- A stream hides the low level device dependent complexities from C program.
- In a C program, all input and Output is done through streams.
- Three streams gets automatically attached when a program starts execution that is
- Standard Input Stream(stdin)
- Standard Output Stream(stdout)
- Standard Error Stream(stderr)
- Keyboard is associated with stdin stream.
- Screen is associated with stdout stream.
FILE Pointer in C
A file pointer is a pointer to a structure of type FILE. A file pointer is associated with stream and manages all Input and Output operations of that stream. The FILE structure contains information which is required to perform any file I/O operations like name of the file, current location of position indicator in file, data transfer bugger, status flag etc.
A file pointer is a bridge between c program and file/stream. We can declare a FILE pointer as follows:
- To perform any I/O operation on file, we need FILE pointer.
- FILE Structure is defined in stdio.h header file.
- FILE Structure contains necessary information about a stream, which is required to perform I/O operation in that stream.
- FILE pointer is an interface for our programs to interact with files.
Opening a File in C
The stdio.h library function fopen() is used to create a new file or open an exiting file.
FILE *fopen(const char *filename, const char *mode);
Function fopen() opens the file whose name is given in the filename argument and associate it with a stream and return a FILE pointer to be used in any future I/O operations on this stream. The fopen function opens a stream in a particular mode, which defines the operations that are allowed on the stream.
Various Modes of Opening a FileMode | Description |
---|---|
"r" | To read a file. Opens a file for reading. The file must exist. |
"w" | To write on a file. Creates an empty file for writing. If a file already exists with same name, its content is removed and the file is considered as a new empty file. |
"a" | To append data at the end of file. The file is created if it does not exist. |
"r+" | To read and write on an existing file. Opens a file to update both reading and writing. The file must exist. |
"w+" | To create a new file for reading and writing. |
"a+" | To read and append data on a file. |
C Program to Open a File using fopen Function
The following program shows the use of fopen function to open a text file in read mode.
#include <stdio.h> int main(){ FILE *file; int ch; /* Open a file for reading */ file = fopen("textFile.txt","r"); if(file == NULL){ perror("Error: Unable to open a file"); } else { while(!feof(file)){ ch = fgetc(file); printf("%c", ch); } fclose(file); } return(0); }Output
fopen C Standard library function
Closing a File in C
The stdio.h library function fclose() is used to close a stream that was opened by fopen() function. Before closing a stream it flushes it's buffer.
int fclose(FILE *stream);
Function fclose closes a stream whose file pointer is passed as argument. If a call to fclose is successful it returns zero, otherwise EOF is returned.
C Program to Close a File using fclose Function
The following program shows the use of fclose function to close a file(stream) after writing a sentence in it.
#include <stdio.h> int main (){ FILE * pFile; /* Creates a new file */ pFile = fopen ("TextFile.txt","w"); /* Write a sentence in a file */ fprintf (pFile, "fclose C standard library function"); /* Close a file */ fclose (pFile); return 0; }Output
fclose C standard library function
Reading from a File in C
The stdio.h standard library provides a number of functions to read data from a stream.
Functions to read a single character from a fileFunction | Description |
---|---|
fgetc() | Reads a character from the given stream. |
getc() | Reads a single character from given stream. |
getchar() | Reads a single character from stdin stream. |
Function | Description |
---|---|
fgets() | Reads a line from given stream and stores it into a character array. |
gets() | Reads a line from stdin and stores it into given character array. |
Function | Description |
---|---|
fscanf() | Read formatted data from given stream. |
scanf() | Reads formatted data from stdin. |
C Program to read formatted data from a file using fscanf function
The following program shows the use of fscanf function to read formatted data from a stream.
#include <stdio.h> int main() { char string[50]; int val; float fval; FILE *file; file = fopen ("textFile.txt", "w+"); fprintf(file, "%d %f %s", 5, 5.5, "TechCrashCourse.com"); rewind(file); fscanf(file, "%d %f %s", &val, &fval, string); printf("Integer : %d\n", val); printf("Floating point number : %f\n", fval); printf("String : %s\n", string); fclose(file); return(0); }Output
Integer : 5 Floating point number : 5.500000 String : TechCrashCourse.com
Writing to a File in C
The stdio.h standard library provides a number of functions to write data on a stream.
Functions to write a single character on a fileFunction | Description |
---|---|
fputc() | Writes a character to the given stream. |
putc() | Writes a character to the given stream. |
putchar() | Writes a character to stdout stream. |
Function | Description |
---|---|
fputs() | Writes a string to the given stream excluding the null terminating character. |
puts() | Writes a string to stdout stream excluding null terminating character. |
Function | Description |
---|---|
fprintf() | Writes formatted output to a stream. |
printf() | Print formatted data to stdout. |
vfprintf() | Writes formatted data to a stream using an argument list. |
vprintf() | Print formatted data to stdout using an argument list. |
vsprintf() | Writes formatted data to a string using an argument list. |
C Program to write formatted data on a file
#include <stdio.h> int main (){ int c, counter = 0; FILE *file; char *string = "fprintf C Standard Library function"; /* Create a temporary file */ file = fopen("textFile.txt", "w"); fprintf(file, "%s", string); fclose(file); /* Opening textFile.txt and printing it's content */ file = fopen("textFile.txt", "r"); while(!feof(file)){ c = fgetc(file); printf("%c", c); } return(0); }Output
fprintf C Standard Library function
Standard Library function for File Handling in C
There are many file handling functions defined in stdio.h header file. Here is the list of frequently used file handling functions:
Function | Description |
---|---|
clearerr() | Clears error indicators associated with a given stream. |
fclose() | Closes the stream and flushes buffers associated with the given stream. |
feof() | Checks the end-of-file indicator of the given stream. |
ferror() | Checks the error indicator of the given stream. |
fflush() | Flushes the content of the given stream. |
fgetc() | Gets the next character from the given stream. |
fgetpos() | Gets current position of the given stream. |
fgets() | Reads a line from given stream and stores it into a character array. |
fopen() | Opens a file in the given mode. |
fprintf() | Writes formatted output to a stream. |
fputc() | Writes a character to the given stream. |
fputs() | Writes a string to the given stream excluding the null terminating character. |
fread() | Reads data from the given stream and stores it into an array. |
freopen() | Reopens a stream with different file or mode. |
fscanf() | Read formatted data from given stream. |
fseek() | Changes the position indicator of the given stream. |
fsetpos() | Sets the position indicator of the given stream. |
ftell() | Returns the current position of the given stream. |
fwrite() | Writes data from an array to the given stream. |