Text File in C

Below program is used to create, read and write text(.txt) files in C.

File is used to store data or information in a storage device permanently. In C, files are handled by the set of file handling methods. In C, file handling operations are

  1. fopen()  – is a function which is used to open a file.
    fopen(const char *filename, const char *operationmode);


      • filename  – contain the name of the file
      • operationmode – indicate the file access mode


Mode Description
r to open a file to read only. The file must exist.
w to create a file to write. If file exist, existing content will be erased. If file not exist, the file has been created and write the content on it.
r+ to open a file to read and write. the file must exist.
w+ to create a file to read and write.
a to open a file to read and append at the end of the file. If file not exist, file has been created.
a+ to open a file to read and append.


void main()
FILE *fp;
char c;
printf("\nEnter the text to store into the files: \n\n");
printf("\nThe content in the file is: \n\n");

In the above program, the text file “a2zinfos.txt” is opened if exist or created if not exist in write mode and text is entered by the users, each character fetched by the function getchar() and write on the file until the entered is pressed(EOF).

Again the same text file “a2zinfos.txt” is opened in read mode. Each character from the file is fetched by the function getc() and shown in screen by the function printf() until the end of the file(EOF).

getchar() is a function which used to fetch the character from the user.

putc() is a function which used to write the character in the file.

putc(char c, FILE file);


getc() is a function which used to read the character from the file.

getc(FILE file);


fclose() is used to close the file. It is important to close the file which helps to clear the cache memory.

fclose(FILE file);


EOF = End Of File

Leave a Reply