File I/O in C Programming
File I/O in C Programming
A File can be used to store a large volume of persistent data. Like many other
languages ‘C’ provides following file management functions,
1. Creation of a file
2. Opening a file
3. Reading a file
4. Writing to a file
5. Closing a file
Following are the most important file management functions available in ‘C’,
function purpose
fopen () Creating a file or opening an existing file
fclose () Closing a file
fprintf () Writing a block of data to a file
fscanf () Reading a block data from a file
getc () Reads a single character from a file
putc () Writes a single character to a file
getw () Reads an integer from a file
putw () Writing an integer to a file
fseek () Sets the position of a file pointer to a specified location
ftell () Returns the current position of a file pointer
rewind () Sets the file pointer at the beginning of a file
How to Create a File
Whenever you want to work with a file, the first step is to create a file. A file is
nothing but space in a memory where data is stored.
<pre>FILE *fp;
</pre>
In the above syntax, the file is a data structure which is defined in the standard
library.
fopen is a standard function which is used to open a file.
If the file is not present on the system, then it is created and then
opened.
If a file is already present on the system, then it is directly opened using
this function.
Whenever you open or create a file, you have to specify what you are going to
do with the file. A file in ‘C’ programming can be created or opened for
reading/writing purposes. A mode is used to specify whether you want to open
a file for any of the below-given purposes. Following are the different types of
modes in ‘C' programming which can be used while working with a file.
In the given syntax, the filename and the mode are specified as strings hence
they must always be enclosed within double quotes.
Example:
<pre>#include <stdio.h>
int main() {
FILE *fp;
</pre>
Output:
File is created in the same folder where you have saved your code.
You can specify the path where you want to create your file
<pre>#include <stdio.h>
int main() {
FILE *fp;
}</pre>
<pre>fclose (file_pointer);
</pre>
Example:
<pre>FILE *fp;
fclose (fp);
</pre>
The fclose function takes a file pointer as an argument. The file associated with
the file pointer is then closed with the help of fclose function. It returns 0 if close
was successful and EOF (end of file) if there is an error has occurred while file closing.
After closing the file, the same file pointer can also be used with other files.
Writing to a File
In C, when you write to a file, newline characters '\n' must be explicitly added.
- fprintf(file_pointer, str, variable_lists) :it prints string to the file pointed to by file_pointer.
String can optionally include format specifiers and a list of variables variable_lists.
The program below shows how to perform writing to a file using:
Fputc() function:
<pre>
#include <stdio.h>
int main() {
int i;
FILE *fptr;
char fn[50];
char str[]="Hello,I'm a programmer\n";
fptr = fopen("fputc_test.txt", "w"); // "w" defines "writing mode"
for (i=0;str[i]!='\n';i++){
/* write to file using fputc() function */
fputc(str[i],fptr);}
fclose(fptr);
return 0 ;}
</pre>
OUTPUT:
The previous program writes a single character into the fputc_test.txt file until it reaches the next
line symbol “\n” which indicates that the sentence was successfully written.
The process is to take each character of the character array and write it into the file after that we
close the file when the string is finished.
Fputs () Function:
<pre>
#include <stdio.h>
int main () {
FILE *fp;
fp = fopen("fputs_test.txt", "w+");
fputs("I'm trying to write with fputs () function ,", fp);
fputs("this is a useful function .\n", fp);
fputs("Take care dear programmer\n", fp);
fclose(fp);
return(0);
}
</pre>
OUTPUT:
OUTPUT:
- fgetc(file_pointer) it returns the next character from the file pointed to by the file pointer,
and when the end of the file has been reached, the EOF is sent back.
- fgets(buffer, n, file_pointer) it reads n-1 characters from the file and stores the string in a
buffer in which the NULL character '\0' is appended as the last character. If fgets()
encounters a newline character or the end of file the characters before (n-1) are stored in the
buffer.
- fscanf(file_pointer, conversion_specifiers, variable_adresses): it is used to parse and analyze
data .it reads characters from the file and assigns the input to a list of variable pointers
variable_adresses using conversion specifiers.
Keep in mind that as with scanf, fscanf stops reading a string when space or newline is
encountered.
The following program demonstrates reading from fputs_test.txt file using fgets(),fscanf() and fgetc
() functions respectively :
<pre>
#include <stdio.h>
int main() {
FILE * file_pointer;
char buffer[30],c;
<pre>
----read a line----
I am learning C
2. We reopen the file in order to reset the pointer file to point in the
begging of the file .We create various strings variables in order to
handle each word separately. After that we print the variables to see
their contents. The fscanf() is mainly used to extract and parse data
from a file .
3. We reopen the file in order to reset the pointer file to point in the
begging of the file .We read data and print it from the file character by
character using getc() function until the EOF statement is encountered
These are the simplest file operations. Getc stands for get character, and putc
stands for put character. These two functions are used to handle only a single
character at a time.
int main() {
FILE * fp;
char c;
printf("File Handling\n");
//open a file
fp = fopen("demo.txt", "w");
//writing operation
putc(c, fp);
//close file
fclose(fp);
printf("Data Entered:\n");
//reading
fp = fopen("demo.txt", "r");
printf("%c", c);
fclose(fp);
return 0;
</pre>
Output:
1. In the above program we have created and opened a file called demo in
a write mode.
2. After a write operation is performed, then the file is closed using the
fclose function.
3. We have again opened a file which now contains data in a reading
mode. A while loop will execute until the eof is found. Once the end of
file is found the operation will be terminated and data will be displayed
using printf function.
4. After performing a reading operation file is again closed using the fclose
function.
Summary
A file is a space in a memory where data is stored.
‘C’ programming provides various functions to deal with a file.
A mechanism of manipulating with the files is called as file management.
A file must be opened before performing operations on it.
A file can be opened in a read, write or an append mode.
Getc and putc functions are used to read and write a single character.
The function fscanf() permits to read and parse data from a file
We can read (using the getc function) an entire file by looping to cover all the file until the
EOF is encountered
We can write to a file after creating its name, by using the function fprintf() and it must have
the newline character at the end of the string text.