Previous Next

C Files

File handling in C is a basic programming concept that allows you to read and write system files. It includes opening the file, reading data from it, writing data to it, and closing it once done.

Types of Files in C

There are two types of files:

Text Files

A text file has only text data such as alphabets, numbers, and special characters. A.txt file is an example of a text file.

Binary Files

A binary file is just a bunch of bytes. A good example of a binary file is a .bin file.

C File Operations

Various operations can be done on a file. These include:

Creating a File

To create a file in C, use the fopen() function with the proper mode.

Syntax

FILE *fptr;
fptr = fopen("filename.txt", "w");

Open a File

To read a file, use the fopen() function.

Syntax

FILE* fopen("fileopen","mode");

Reading From a File

Employ the operations such as fscanf(), fgets() to fetch information from the file.

Syntax

FILE *fptr;
fptr = fopen("filename.txt", "r");

Write to a File

Utilize the functions such as fprintf(), fputs() to print data into the file.

Syntax

FILE *fptr;
fptr = fopen("filename.txt", "w");
fprintf(fptr, "Hello C");
fclose(fptr);

Closing a File

Once we have done reading from the file, we must close it. This is achieved through the use of the fclose() function.

Syntax

fclose(fp);

Example:

#include <stdio.h>

int main()
{
    int i = 0;

    do
    {
        printf("%d", i);
        i++;
    } while (i < 4);

    return 0;
}

Output:

0 1 2 3
Previous Next