Categories: C

File handling in C

File handling in C allows us to use our C program to create, update, read, and delete files stored on the local file system. A file can be subjected to the following operations:

  • Making a new file
  • Choosing an existing file to open
  • Taking a page from the file
  • Adding to the file
  • removing the file
Function of file handling in c:
Function Description
fopen() fopen() creates or opens a new or existing file
fprintf() fprintf() writes data to a file
fscanf() The fscanf() function reads data from a file.
fputc()fputc() inserts a character into the file.
fgetc()The function fgetc() reads a character from a file.
fclose() fclose() closes a file.
fseek() fseek() moves the file pointer to the specified position.
fputw() fputw() saves an integer to a file.
fgetw()fgetw() retrieves an integer from a file.
ftell() ftell() returns the current position.
rewind()rewind() returns the file pointer to the start of the file.
File opening:

To open an existing file or create a new one, use the fopen() function. This call will create an object of type FILE that contains all the information required to control the stream. This function call’s prototype is as follows:

FILE *fopen( const char * filename, const char * mode );
Sr.No.Mode & Description
1r
Opens a previously saved text file for reading.
2w
Allows you to write in a text file. If it does not already exist, a new file is created. In this case, your program will begin writing content at the beginning of the file.
3a
Opens a text file in appending mode for writing. If it does not already exist, a new file is created. At this point, your program will begin appending content to the existing file content.
4r+
This command opens a text file for both reading and writing.
5w+
This command opens a text file for both reading and writing. If the file already exists, it is truncated to zero length; otherwise, a file is created if it does not exist.
6a+
This command opens a text file for both reading and writing. If the file does not already exist, it is created. The reading will begin at the beginning, but writing can only be added at the end.

Instead of the access modes listed above, use the ones listed below to handle binary files.

"rb", "wb", "ab", "rb+", "r+b", "wb+", "w+b", "ab+", "a+b"
Closing a File:

Use the fclose() function to close a file. This function’s prototype is.

int fclose(FILE *fp); 

The fclose(-) function returns zero if the file is successfully closed, or EOF if an error occurs. This function actually flushes any pending data in the buffer to the file, closes the file, and releases any memory used by the file. The EOF is a constant defined in the stdio.h header file.

Writing a File:

The following is the most basic function for writing individual characters to a stream:

int fputc(int c, FILE *fp); 

The function fputc() writes the argument c’s character value to the output stream referenced by fp. If successful, it returns the written character; otherwise, it returns EOF if there is an error.

#include <stdio.h>

main() {
   FILE *fp;

   fp = fopen("/tmp/test.txt", "w+");
  
   fputc("This is testing for fputc...\n", fp);
   fclose(fp);
}

When the preceding code is compiled and executed, it creates a new file called test.txt in the /tmp directory and writes the sentence into it.

Reading a Document:

The simplest function for reading a single character from a file is shown below.

int fgetc(FILE * fp); 

The fgetc() function reads a character from the fp-referenced input file. The return value is the character read, or EOF if an error occurs. The following function reads a string from a stream.

char *fgets(char *buf, int n, FILE *fp);

The fgets() function reads up to n-1 characters from the fp-referenced input stream. It appends a null character to the end of the read string and copies it into the buffer buf.

for, instance:

#include <stdio.h>

main() {

   FILE *fp;
   char buff[255];

   fp = fopen("/tmp/test.txt", "r");
   fscanf(fp, "%s", buff);
   printf("1 : %s\n", buff );

   fgets(buff, 255, (FILE*)fp);
   printf("2: %s\n", buff );
   
   fgets(buff, 255, (FILE*)fp);
   printf("3: %s\n", buff );
   fclose(fp);

}

When the code in the preceding section is compiled and executed, it reads the file created in the previous section.

Similarly, various other operations on a file could be performed in c.

Note: also read about the Pointer to Pointer in C

Follow Me

If you like my post please follow me to read my latest post on programming and technology.

https://www.instagram.com/coderz.py/

https://www.facebook.com/coderz.py

Share
Published by
Rabecca Fatima

Recent Posts

Generate Parenthesis | Intuition + Code | Recursion Tree | Backtracking | Java

Problem Statement: Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. Example…

2 months ago

Square Root of Integer

Given an integer A. Compute and return the square root of A. If A is…

1 year ago

Build Array From Permutation

Given a zero-based permutation nums (0-indexed), build an array ans of the same length where…

1 year ago

DSA: Heap

A heap is a specialized tree-based data structure that satisfies the heap property. It is…

1 year ago

DSA: Trie

What is a Trie in DSA? A trie, often known as a prefix tree, is…

2 years ago

Trees: Lowest Common Ancestor

What is the Lowest Common Ancestor? In a tree, the lowest common ancestor (LCA) of…

2 years ago