File Handling in C

File Handling in C :

File handling in C can be done on Stream oriented (Text) and System Oriented (Binary) files.

Operations on File :

Basic operations performed on a file are :

  • Creating /Opening file
  • Read from file
  • Write/Append into file
  • Closing file

For dealing with files, File pointers are created to handle that file which serve as a link b/w file and program.

Syntax:
FILE *ptr;

OPENING A FILE :

It is used to open an existing file or create a new file.

Syntax: fopen( “ filename/location”,”mode “);

There are various modes to use a file :
r : Opens a file in reading mode and returns NULL if it does not exists.
w : Opens an existing file in writing mode and creates file if it does not exists. The content is overwritten with new content in existing file.
a : Opens files and appends data at the end of file and creates file if it does not exists.
r+ : Opens file in both read and write mode and returns NULL if it does not exists.
w+ : Opens file in both read and write mode and creates file if it does not exists. The content is overwritten with new content in existing file.
a+ : Opens file in both read and append mode and creates file if it does not exists. The file is apppened with new content in existing file.
e.g.
File *ptr=fopen(“file.txt”,”w”);

WRITING INTO FILE :

The functions used to read contents from a file are :
fputc : Writes a single character into a file. Returns the written character on success else EOF.
fprintf : It writes strings into a file,
fputs : It writes strings into a file. Returns a positive value on success else returns EOF.

In this program, a file is created with name “program.txt”. Inputing string as “Hi Progspace” and thats get written in file using fprintf() and then “ Hye” is written using fputs() function. Similar, code can be used for appending the file. Write “a” instead of “w” to append data at the end of existing file.

READING FROM A FILE :

The functions used to read contents from a file are :
fgetc : Read a single character from a file.
fscanf : It reads strings from a file but it stops reading after the first space character is encountered.
fgets : Read a string from file but it stops reading after a newline or EOF or EOL is encountered. It copies the read string into buffer appending a null character at the end.

Output:
String in file is Hi

Remaining String in file is Progspace Hye
fscanf() reads until first space is encountered i.e. ”Hi” an d remaining is read by calling fgets().

Closing File :

fclose() function is used to close the opened file.

Syntax:

fclose(filename);

Leave a Reply

Your email address will not be published. Required fields are marked *