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.
    //SYNTAX
    fopen(const char *filename, const char *operationmode);
    

    PARAMETERS:

      • 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.

 

#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fp;
char c;
clrscr();
fp=fopen("a2zinfos.txt","w");
printf("\nEnter the text to store into the files: \n\n");
while((c=getchar())!=EOF)
  putc(c,fp);
fclose(fp);
fp=fopen("a2zinfos.txt","r");
printf("\nThe content in the file is: \n\n");
while((c=getc(fp))!=EOF)
  printf("%c",c);
fclose(fp);
getch();
}

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.

//SYNTAX
putc(char c, FILE file);

 

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

//SYNTAX
getc(FILE file);

 

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

//SYNTAX
fclose(FILE file);

 

EOF = End Of File

Leave a Reply