C Programming
In this tutorial we will learn to read and write characters in files in C programming language.
We have already learned how to create files in C in the previous tutorial. Feel free to check that out.
We use the getc()
and putc()
I/O functions to read a character from a file and write a character to a file respectively.
Syntax of getc:
char ch = getc(fptr);
Where, fptr
is a file pointer.
Note! EOF
marks the End-Of-File. And when we encounter EOF character it means we have reached the end of the file.
Syntax of putc:
putc(ch, fptr);
Where, ch
is the character to write and fptr
is a file pointer.
For this we will first create a FILE
pointer and create a file by the name username.txt
. Feel free to use any other filename that you like.
Then we will use the putc()
function to write the characters in the file.
Once that is done we can then use the getc()
function to read the file data till we hit the EOF and show it in the console.
Complete code:
#include <stdio.h>
int main(void) {
// creating a FILE variable
FILE *fptr;
// creating a character variable
char ch;
// open the file in write mode
fptr = fopen("username.txt", "w");
// take user input
printf("Enter your name: ");
// keep reading the user input from the terminal
// till Return (Enter) key is pressed
while( (ch = getchar()) != '\n' ) {
// write character ch in file
putc(ch, fptr);
}
// close the file
fclose(fptr);
// open the file in read mode
fopen("username.txt", "r");
// display the content of the file
printf("\nFile content:\n");
while( (ch = getc(fptr)) != EOF ) {
printf("%c", ch);
}
printf("\nEnd of file\n");
// close file
fclose(fptr);
return 0;
}
Output:
Enter your name: Yusuf Shakeel
File content:
Yusuf Shakeel
End of file
Content of the file:
ADVERTISEMENT