File Handling in C, In Just A Few Hours!

file handling in c Aticleworld

Sometimes we require persistent data in our C program, in that situation knowledge of file handling in C is very helpful. So you should have the basic knowledge of file handling in C. Basically, file represents a sequence of bytes that store in the disk permanently.

Previously, I had worked on a restaurant application( Vx520 POS Terminal). Where I do the tip adjustment on the basis of trace number.  So I had stored amount and tax in the binary file and parsed it as per the trace number.

There are many functions for file handling in C, I have mentioned below a few file handling functions in C.

fopen(),      getc(),       putc(),     fclose()
fprintf(),    fscanf(),     fgets(),    fputs()
rewind(),     fseek(),      ftell(),    fflush()
fgetpos(),    fsetpos(),    feof(),     ferror()
ungetc(),     setvbuf(),    fread(),    fwrite()

 

 

File handling in C enables us to create, update, read, write and delete the files using the C program. In this article, I will discuss C file operation function with their examples, like the creation of a file, opening a file, reading file, etc.

Opening a File or Creating a File:

The fopen() function is used to create a new file or open an existing file. It is declared in stdio.h. It has two arguments, its first argument is the name of the file to be created or opened. The second argument is the mode of the file in which it is created or opened. These modes are predefined if you are not using these modes then the behavior would be undefined.

Syntax of fopen():

FILE *fopen(const char * restrict filename,const char * restrict mode);

 

Parameters of fopen():

1. filename: pointer to a character for the file name.

2. mode: pointer to a character for file mode.

 

Return value of fopen():

The fopen function returns a pointer to the object controlling the stream. If the open
the operation fails, fopen returns a null pointer.

 

Example code to create a file:

In the below code, I am creating a text file using the fopen() function.

#include <stdio.h>

int main()
{
    FILE *fp = NULL;

    //create a text file
    fp  = fopen ("aticleworld.txt", "w");
    if(fp == NULL)
    {
        printf("File is not created\n");
        exit(1);
    }
    else
    {
        printf("File is created\n");
    }
    //close the file
    fclose(fp);

    return 0;
}

 

Output:

If fopen() create file successfully, the text file will be created in the same folder where you have saved your code. Like the below image.

file handling in c

 

 

If you want to create or open the file at a specified location, you have to give the path in fopen.

#include <stdio.h>

int main()
{
    FILE *fp = NULL;

    //create a text file
    fp  = fopen ("F://data.txt", "w");
    if(fp == NULL)
    {
        printf("File is not created\n");
        exit(1);
    }
    else
    {
        printf("File is created\n");
    }
    //close the file
    fclose(fp);

    return 0;
}

 

Output:

If fopen() create file successfully, the text file will be created F drive. You can see the below image.

 

C file handling

 

You can see this article,

 

Closing a file:

The fclose() function is used to close an already opened file. A successful call to the fclose function is flush the pending data of buffer, close the file and releases any memory used for the file. It takes only one argument that is file pointer return by fopen().

Syntax of fclose():

int fclose(FILE *stream);

 

Return of fclose():

The fclose function returns zero if the stream was successfully closed, or EOF if any
errors were detected.

 

Writing to a File:

Here, I have mentioned some functions which are used to write data into the file.

1. Formated output functions for file:

fprintf()

The fprintf function is used to write the formatted data to the stream pointed to by stream. The arguments of fprintf function are similar to the printf function except that fprintf has an extra argument which is a file pointer (first argument). This file pointer tells the file where the formatted output will be written.

Note: In fprintf, if there are insufficient arguments for the format, the behavior is undefined.

Syntax of fprintf():

int fprintf(FILE * restrict stream, const char * restrict format, ...);

 

Return value of fprintf():

On success, fprintf function returns the total number of characters written (transmitted)and on error return a negative number.

 

Example code to explain the working of fprintf function

Below example ask the student name 3 times and writes them to aticleworld.txt.

#include <stdio.h>

int main()
{
    //file pointer
    FILE *fp = NULL;
    int i = 0;
    char name[40] = {0};
    //create a text file
    fp  = fopen ("aticleworld.txt", "w");
    if(fp == NULL)
    {
        printf("File is not created\n");
        exit(1);
    }

    //three times asking for
    //student name
    for (i=1 ; i<4 ; i++)
    {
        puts ("Enter the student name: ");
        //Get input from the user
        gets (name);
        //Write formated data into the file
        fprintf (fp, "%d. Name  = [%s]\n",i,name);
    }

    //close the file
    fclose(fp);

    return 0;
}

 

Output:

fprintf in c

 

 

2. Character output functions for file

fputc():

The fputc() function writes the character (unsigned char) to the output stream, at the specified position (indicated by the associated file position indicator) and then advances the indicator appropriately.

Syntax of fputc()

int fputc(int c, FILE *stream);

 

Return value of fputc():

If fputc has written the character successfully, then return the written character. If there is any error, then it returns EOF.

 

Example code for fputc,

In the below code, I am writing A-Z in the newly created file (aticleworld.txt)  using the fputc function.

#include <stdio.h>

int main()
{
    int ch = 0;
    FILE *fp = NULL;
    fp = fopen("aticleworld.txt", "w");
    if(fp == NULL)
    {
        printf("Error in creating the file\n");
        exit(1);
    }
    //Write A to Z in file
    for(ch =65 ; ch <= 90 ; ++ch)
    {
        fputc(ch, fp);
    }
    //close the file
    fclose(fp);

    printf("A t0 Z written to the created file\n");

    return 0;
}

 

Output:

fputc in c

 

 

fputs():

The fputs function writes the string pointed to the output stream. The terminating null character is not written to the file. It takes two argument pointer to string and file pointer.

Syntax of fputs

int fputs(const char * restrict s, FILE * restrict stream);

 

Return value of fputs():

On success, the fputs function returns a non-negative value and if a write error occurs, then returns EOF.

 

Example code of fputs,

 

#include <stdio.h>

int main()
{
    //file pointer
    FILE *fp = NULL;
    fp = fopen("aticleworld.txt", "w");
    if(fp == NULL)
    {
        printf("Error in creating the file\n");
        exit(1);
    }

    fputs("Hello There, I hope this article will help!",fp);
    //close the file
    fclose(fp);

    printf("File has been created successfully\n");

    return 0;
}

 

Output:

fputs in c

 

3. Direct output functions

fwrite():

The fwrite function writes nmemb elements from the given array to the output stream.
for each object fputc is called size times (count of bytes for a single element) and file position indicator for the stream is advanced by the number of characters written.

Syntax of fwrite():

size_t fwrite(const void * restrict ptr, size_t size, size_t nmemb,
              FILE * restrict stream);

 

Where,

ptr: Pointer to the array of elements to be written.

size: Size in bytes of each element to be written.

nmemb: Number of elements to be written.

stream: Pointer to the file, where data will be written.

 

Return value of fwrite():

On success, it returns the number of elements successfully written. On error, it returns a number of elements less than nmemb.

 

Note: If the size or nmemb is zero, fwrite returns zero and the state of the output stream remains unchanged.

 

Example code of fwrite,

Below example ask the name from the user and store it in the buffer. After getting the name it writes the name in the created file using the fwrite function.

#include <stdio.h>

//Maximum size of the array
#define MAX_SIZE  32

int main()
{
    //file pointer
    FILE *fp = NULL;
    char buffer[MAX_SIZE] = {0};

    //Get input from the user
    printf("Enter your Name = ");
    fgets(buffer,MAX_SIZE,stdin);

    //create the file
    fp = fopen("aticleworld.txt", "w");
    if(fp == NULL)
    {
        printf("Error in creating the file\n");
        exit(1);
    }

    //Write the buffer in file
    fwrite(buffer, sizeof(buffer[0]), MAX_SIZE, fp);

    //close the file
    fclose(fp);

    printf("File has been created successfully\n");

    return 0;
}

 

Output:

fwrite in c

 

 

Reading from a File:

Like the writing function here, I have mentioned some functions which are using in file reading.

1. Formated input functions for file:

fscanf():

The fscanf function is used to read the formatted data from the stream pointed to by stream. The arguments of fscanf function are similar to the scanf function except that fscanf has an extra argument which is a file pointer (first argument). This file pointer tells the file from the formatted input will be read.

Syntax of fscanf():

int fscanf(FILE * restrict stream, const char * restrict format, ...);

 

Note: In fscanf, if there are insufficient arguments for the format, the behavior is undefined.

 

Return value of fscanf():

On success, fscanf function returns the total number of input read and on error or at the end of the file return EOF.

 

Example code to explain the working of fscanf function,

In the below code, I am reading a file using the fscanf. The file “aticleworld.txt” contains a string “Aticleworld..”.

#include <stdio.h>

//Maximum size of the array
#define MAX_SIZE  32

int main()
{
    //file pointer
    FILE *fp = NULL;
    char readFileData[MAX_SIZE+MAX_SIZE] = {0};

    //open file
    fp = fopen("aticleworld.txt", "r");
    if(fp == NULL)
    {
        printf("Error in creating the file\n");
        exit(1);
    }

    //read file data
    fscanf(fp,"%s",readFileData);

    //Display read data
    puts(readFileData);

    //close the file
    fclose(fp);

    printf("Read file successfully\n");

    return 0;
}

 

Output:

fscanf in c

 

 

2.Character input functions for file

fgetc():

The fgetc() function read a single character from the stream and return their ASCII value. After reading the character, it advances the associated file position indicator for the stream.

Syntax of fgetc():

int fgetc(FILE *stream);

 

Return value of fgetc():

On success, it returns the ASCII value of the character. On error or end of the file, it returns EOF.

Example code to explain the working of fgetc function,

In the below code, I am reading a file using the fgetc. The file “aticleworld.txt” contains a string “I love File handling.”.

#include <stdio.h>

int main()
{
    //file pointer
    int ch = 0;
    FILE *fp = NULL;

    //open the file
    fp = fopen("aticleworld.txt", "r");
    if(fp == NULL)
    {
        printf("Error in opening the file\n");
        exit(1);
    }

    while( (ch=fgetc(fp)) != EOF )
    {
        //Display read character
        printf("%c", ch);
    }

    //close the file
    fclose(fp);

    printf("\n\n\nRead file successfully\n");

    return 0;
}

 

Output:

fgetc in c

 

fgets():

The fgets function reads characters from the specified stream and store into the character array.
It reads only n-1 character, where n is the specified number of characters.

It stops the reading when read newline character or (n-1) character, or encounter end-of-file. The good thing is that it writes null character just after written the last character into the array.

Syntax of fgets:

char *fgets(char * restrict s, int n,FILE * restrict stream);

 

Return value of fgets():

On success, the fgets function returns the string (same s parameter). On error return null pointer.

Note: If end-of-file is encountered and no characters have been read into the “s” (character array), the contents of the “s” remain unchanged and a null pointer is returned.

 

Example code to explain the working of fgets function,

In this example, I am reading a file “aticleworld.txt” using the fgets which contains a string “I am using fgets.”.

#include <stdio.h>

//Maximum size of the array
#define MAX_SIZE  32

int main()
{
    //file pointer
    FILE *fp = NULL;
    char readFileData[MAX_SIZE] = {0};

    //open the file
    fp = fopen("aticleworld.txt", "r");
    if(fp == NULL)
    {
        printf("Error in opening the file\n");
        exit(1);
    }

    //Read file using fgets
    if(fgets(readFileData,MAX_SIZE,fp) == NULL)
    {
        printf("Error in reading the file\n");
        //close the file
        fclose(fp);
        exit(1);
    }

    //Display read data
    puts(readFileData);

    //close the file
    fclose(fp);

    printf("Read file successfully\n");

    return 0;
}

 

Output:

fgets in c

 

 

3.Direct input function:

 

fread():

The fread function reads nmemb elements from the given stream to the given array.
for each element, fgetc is called size times (count of bytes for a single element) and file
position indicator for the stream is advanced by the number of characters read.

Syntax of fread:

size_t fread(void * restrict ptr, size_t size, size_t nmemb,
             FILE * restrict stream);

 

Where,

ptr: Pointer to a block of memory with a minimum size of size*nmemb bytes.

size: Size in bytes of each element to be read.

nmemb: Number of elements to be read.

stream: Pointer to the file, from where data will be read.

 

Return value of fread():

On success, it returns the number of elements successfully read. On error, it returns a number of elements less than nmemb.

Note: If the size or nmemb is zero, fread returns zero and the contents of the array and the state of the input stream remain unchanged.

 

Example code of fread,

In this example, I am reading 6 characters from the file “aticleworld.txt” using the fread function.

#include <stdio.h>

//Maximum size of the array
#define MAX_SIZE  32

int main()
{
    //file pointer
    FILE *fp = NULL;
    char readFileData[MAX_SIZE] = {0};

    //open the file
    fp = fopen("aticleworld.txt", "r");
    if(fp == NULL)
    {
        printf("Error in opening the file\n");
        exit(1);
    }

    // Read 5 character from stream
    fread(readFileData,sizeof(char),6, fp);

    //Display read data
    puts(readFileData);

    //close the file
    fclose(fp);

    printf("Read file successfully\n");

    return 0;
}

 

Output:

fread in c

 

Change the position of the file indicator:

 

fseek():

The fseek function sets the file position indicator of the stream to the given offset. Three-position (whence) are given for the fseek, these are SEEK_SET (Beginning of file), SEEK_CUR (Current position of the file pointer), and SEEK_END (End of file). The new position of file indicator is obtained by adding offset to the position specified by whence.

Syntax of fseek():

int fseek(FILE *stream, long int offset, int whence);

Where,

stream: Stream which position indicator will change.
offset: This is the number of bytes to offset from whence.
whence: position from where the offset is added. It is specified by one of the following constants, SEEK_SET, SEEK_CUR or SEEK_END.

 

Return value of fseek():

On success, it returns the zero. On error, it returns a non-zero number.

 

Example code of fseek,

In below example code, I am shifting the file position indicator by 1 using the fseek function and read the character using the fgetc.

#include <stdio.h>


int main()
{
    //file pointer
    FILE *fp = NULL;
    int ch =0;

    //open the file
    fp = fopen("aticleworld.txt", "r");
    if(fp == NULL)
    {
        printf("Error in opening the file\n");
        exit(1);
    }

    //Shift file position indicator by 1
    fseek( fp,1, SEEK_SET );

    //Read 1 character
    ch = fgetc(fp);

    //Display read character
    printf(" %c\n", ch);

    //close the file
    fclose(fp);

    return 0;
}

 

Output:

fseek in c

 

rewind()

The rewind function sets the file position indicator to the beginning of the file. It equivalent to (void)fseek(stream, 0L, SEEK_SET).

Syntax of rewind():

void rewind(FILE *stream);

 

Return value of rewind():

The rewind function returns no value.

 

 

ftell():

The ftell function returns the current value of the file position indicator for the given stream.

Syntax  of ftell():

long int ftell(FILE *stream);

 

Return value of ftell():

On success, it returns the current value of the file position indicator for the stream. On error, it returns −1L and stores an implementation-defined positive value in errno.

 

I hope, after reading “file handling in C”, you able to manipulate the file as per the requirement. I will update this article regularly and help you to understand the “file handling in C” better way!

Recommended Articles for you:

 



Leave a Reply

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