C Program to Create a File & Store Information

C Program to Create a File & Store Information

C program to create a file and store information in it. In this article, I will explain, how to create a file in C programming and also write data in it. If you are not familiar with the file handling function, you should read the below article.

Learn file handling in C, in a few hours.

 

Example C Program to Create a File & Store Information:

In this code, I am creating the file in write mode using the fopen function. If the file opened successfully, then code asking input from the user and store it in created file.

#include <stdio.h>

//Maximum size of the array
#define MAX_SIZE  200

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

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

    //Get input from the user
    printf("Enter data which you want to store = ");
    if(fgets(buffer,MAX_SIZE,stdin) == NULL)
    {
        printf("Error in reading the input data\n");
        //close the file
        fclose(fp);
        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 and saved successfully\n");

    return 0;
}

Output:

create and save data in file in C

 

Code Analysis:

In the above c example, first, I have created the file (“aticleworld.txt”)  using the “w” mode and get the file pointer. Using the if condition I am verifying that file is created successfully or not.

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

 

After creating the file successfully, I have used fgets to read the input data and store it in a character array. I have also used the if condition to check whether fgets reads input data without error or not.

if(fgets(buffer,MAX_SIZE,stdin) == NULL)
{
    printf("Error in reading the input data\n");
    //close the file
    fclose(fp);
    exit(1);
}

 

In the last, I have used fwrite to write the read data in the created file and close the file using fclose function. You can also see the article “How to use fwrite in C“.

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

//close the file
fclose(fp);

 

Recommended Articles for you:



Reference: File input-output.