Loading...
Loading...
00:00:00

File Handling

File Handling is used to store data in a local storage in the form of file. Whenever we run the program all variables are initialize in the memory, they perform operation and store results in variable itself. After closing the program the whole data on those variables will be destroy from memory and we can't access next time when reopen the program. we can use File Handling technique to get rid of data loss.

In file handling , There is four major operation we have to perform such as Create, Read, Update and delete or CRUD. Before using file we have to Include stdio.h header file.

  • Create file
  • Write in File
  • Read from file
  • Modify
  • Delete

Open And Close File

fopen() function is used to open file and fclose() is used to close file. After All file operations done you must close the file.

Syntax for Open a file and close file.

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char const *argv[])
{
    FILE *file_pointer;                        // create a file pointer
    file_pointer = fopen("filename.txt", "opening_Modes"); // open file with filename and opening mode
    // some file operation code
    fclose(file_pointer);                      // close the file after operation complete
    return 0;
}

File Opening Modes And Their Uses

File Opening Modes Description
r open file in read mode for reading if file not found fopen() return NULL
w Open in 'write mode' if file exist data will be over written or file length zero else create new file and write.
a Open in append mode if file exist data appended at the end of old data else create new file and write.
r+ open file in read and write mode but it does not create a new file if file not exist.
w+ open file in read and write mode, first truncates the file length zero if file exists or creating the a file if does not exist.
a+ open file in read and append mode, if it not exits create a file and append.
rb open file in read mode in binary format for reading if file not found fopen() return NULL
wb Open in write mode in binary format if file exist data will be over written or file length zero else create new file and write.
ab Open in append mode in binary if file exist data appended at the end of old data else create new file and write.
rb+ Open in read mode in binary format for reading and writing. It does not create file.
wb+ open in write mode in binary format for reading and writing. if file exist content will be erased. if file does not exits create a new file.
ab+ open file in append mode in binary format. if file does not exits create a new file.

Open File In Read Mode

"r" Open file in read mode for reading content from file. if file is not found in the directory fopen() function retruns NULL.

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char const *argv[])
{
    FILE *file_pointer;                        // create a file pointer
    file_pointer = fopen("filename.txt", "r"); // open file in read mode
    if (file_pointer == NULL)
        printf("File Not Found!\n");
    else
        printf("File Opened successfully\n");
    fclose(file_pointer); // close the file after operation complete
    return 0;
}

Open File In Write Mode

Open file in "w" first erased all the if file exist then write. if file not exist create a new file.

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char const *argv[])
{
    FILE *file_pointer; // create a file pointer
    char str[50] = "Open in write mode";
    file_pointer = fopen("filename.txt", "w"); // open file in write mode
    fputs(str, file_pointer);                  // write in file
    if (file_pointer == NULL)
        printf("Cannot create file!\n");
    else
        printf("File created successfully\n");
    fclose(file_pointer); // close the file after operation complete
    return 0;
}

Open File In Append Mode

Open file in "a" append mode. Data will be written at the end of existing data in file. if file does not exist create new file.

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char const *argv[])
{
    FILE *file_pointer; // create a file pointer
    char str[50] = "\nOpen in append mode";
    file_pointer = fopen("filename.txt", "a"); // open file in append mode
    fputs(str, file_pointer);                  // append in file 
    if (file_pointer == NULL)
        printf("Cannot create file!\n");
    else
        printf("File opened successfully in append mode\n");
    fclose(file_pointer); // close the file after operation complete
    return 0;
}

Syntax Of Fputs() And Fgets() Functions

fputs() function is used to write data in file from variables.

int fputs(const char *__restrict__ _Str, FILE *__restrict__ _File)

fgets() function is used to get data from file in variables.

char *fgets(char *__restrict__ _Buf, int _MaxCount, FILE *__restrict__ _File)

Examples Of Fputs()

fputs() function for writing data in file

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char const *argv[])
{
    char str0[] = "hello World";
    FILE *file_pointer;                        // file pointer
    file_pointer = fopen("filename.txt", "a"); // open file
    if (file_pointer == NULL)
        printf("file not open\n");
    fputs(str0, file_pointer); // writing in file
    fclose(file_pointer);      // close the file

    return 0;
}

Examples Of Fgets()

fgets() function for reading data from file

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char const *argv[])
{
    char str0[50];
    FILE *file_pointer;                        // file pointer
    file_pointer = fopen("filename.txt", "r"); // open file in read mode
    if (file_pointer == NULL)
        printf("file not open\n");
    fgets(str0, 30, file_pointer);             // reading from file
    printf("The value in file is %s\n", str0); //print the file data
    fclose(file_pointer);                      // close the file

    return 0;
}

Syntax Of Fputc() And Fgetc()

fputc() is used to write a single character in a file.

int fputc(int _Ch, FILE *_File)

fgetc() is used to read a single character from a file.

int fgetc(FILE *_File)

Example Of Fputc() Function

fputc() function for writing data in file character by character

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char const *argv[])
{
    char ch = 'p';
    FILE *file_pointer;                        // file pointer
    file_pointer = fopen("filename.txt", "w"); // open file in write mode
    if (file_pointer == NULL)
        printf("file not open\n");
    fputc(ch, file_pointer);            // write in file
    fclose(file_pointer);

    return 0;
}

Example Of Fgetc() Function

fgetc() function for reading data from file character by character

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char const *argv[])
{
    char ch;
    FILE *file_pointer;                        // file pointer
    file_pointer = fopen("filename.txt", "r"); // open file in read mode
    if (file_pointer == NULL)
        printf("file not open\n");
    while ((ch = fgetc(file_pointer)) != EOF) // reading all characters from file
    {
        printf("%c", ch);
    };
    fclose(file_pointer);

    return 0;
}

Syntax Of Fprintf() And Fscanf() Functions

fprintf() function is used to write set of characters or string using format specifiers in file.

int fprintf(FILE *__restrict__ _File, const char *__restrict__ _Format, ...)

fscanf() function is used to read set of characters or string using format specifiers from file.

int fscanf(FILE *__restrict__ _File, const char *__restrict__ _Format, ...)

Examples Fo Fprintf() Function

fprintf() function for writing data in file

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char const *argv[])
{
    char str[] = "panditprogrammer.com";
    FILE *file_pointer;                        // file pointer
    file_pointer = fopen("filename.txt", "w"); // open file in write mode
    if (file_pointer == NULL)
        printf("file not open\n");
    fprintf(file_pointer, " You are learning c language at %s \n", str); // write in file
    fclose(file_pointer);

    return 0;
}

Example Of Fscanf() Function

fscanf() function for reading data from file

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char const *argv[])
{
    char str[50];
    FILE *file_pointer;                        // file pointer
    file_pointer = fopen("filename.txt", "r"); // open file in read mode
    if (file_pointer == NULL)
        printf("file not open\n");
    while (fscanf(file_pointer, "%s", str) != EOF) // read from file
    {
        printf("%s ", str);
    };
    fclose(file_pointer);

    return 0;
}