In one of the previous articles, I have mentioned file handling in C++, now in this article, I have provided working program example to open a file in C, write to file in C or read contents of file in C Language.

What is File?

File is a colelction of byte stored on local storage of computer like hard disk. File can be of two types, Binary file with 0/1 text or text files.

Sometimes, we may need to perform various operations like creating a file or updating file, or reading file contents using C programming language, which is also known as File handling in C

So, here are some of the few functions used in file handling of C, which is important to understand, before checking a file program in C.

function description
fopen() opens new or existing file
fprintf() writes data into file
fscanf() reads data from the file
fclose() closes the file
fgets() get user content in a variable
fputs() Write data to file from variable

Here are the operations mode which you can perform on file in C.

mode description
r opens a text file in read mode
w opens a text file in write mode
a opens a text file in append mode
r+ opens file in read and write mode
w+ opens a text file in read and write mode
a+ opens a text file in read and write mode
rb opens a binary file in read mode
wb open binary file in write mode
ab opens a binary file in append mode
rb+ opens a binary file in read and write mode
wb+ opens a binary file in read and write mode
ab+ opens a binary file in read and write mode

C Program to Create and Write to File

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

#define File_Content_Size 1000

int main()
{
    /* Variable to store user content */
    char data[File_Content_Size];

    /* File pointer to hold reference to our file */
    FILE * fPtr;

    /*Open File and write to it, it will also create file if it doesn't exist and write contents*/
    fPtr = fopen("file1.txt", "w");

    /* fopen() return NULL if last operation was unsuccessful */
    if(fPtr == NULL)
    {
        /* File not created hence exit program */
       printf( "Could not open file file1.txt" ) ;
               return 1;
    }

    /* Ask User to add contents of file */
    printf("Enter contents to store in file : \n");
    fgets(data, File_Content_Size, stdin);

    /* Write data to file */
    fputs(data, fPtr);
    /* Close file to save file data */
    fclose(fPtr);

    /* Success message */
    printf("File created and saved successfully. \n");

    return 0;
}

In the above code, we have initially defined Maximum file size using #define File_Content_Size 1000

Once we have started the main function, we are creating a file type pointer *fptr, using which we are opening file or creating, basically we are saving file reference in it.

Once we have tried to create or open file using fopen("file1.txt", "w");, we ask user for contents to enter in file and save it in "data" variable, then using fputs saves content in file.

Here in fopen command, file1.txt is file name and "w" is write mode operation, basically we are opening file in write mode.

Here is the output, when I executed sample code in CodeBlocks IDE

file-open-write-in-c-program-min.gif

Append New Data in File in C

In the above program, we created file and then added contents in it, in this example, we will append data in already created file and then read it's content.

So, we will open file in append mode "fPtr = fopen("file1.txt", "a");" here is the complete code

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

#define File_Content_Size 1000
void readFile(FILE * fPtr);
int main()
{
    /* Variable to store user content */
    char dataToAppend[File_Content_Size];

    /* File pointer to hold reference to our file */
    FILE * fPtr;

    /*Open file in append mode, it will also create file if it doesn't exist and write contents*/
    fPtr = fopen("file1.txt", "a");

    /* fopen() return NULL if last operation was unsuccessful */
    if(fPtr == NULL)
    {
        /* File not created hence exit program */
       printf( "Could not open file file1.txt" ) ;
               return 1;
    }

    /* Ask User to add contents of file */
    printf("\nEnter data to append: ");
    fflush(stdin);          // To clear extra white space characters in stdin
    fgets(dataToAppend, File_Content_Size, stdin);


    /* Append data to file */
    fputs(dataToAppend, fPtr);


    /* Reopen file in read mode to print file contents */
    fPtr = freopen("file1.txt", "r", fPtr);

    /* Print file contents after appending string */
    printf("\nSuccessfully appended data to file. \n");
    printf("Changed file contents:\n\n");
    readFile(fPtr);


    /* Done with file, hence close file. */
    fclose(fPtr);
}

/*read file function*/
void readFile(FILE * fPtr)
{
    char ch;

    do
    {
        ch = fgetc(fPtr);

        putchar(ch);

    } while (ch != EOF);
}

That's it, you can review output, you will see new content is added in file.

You may also like to read:

Simple C programming examples with output (must read for beginners)

Star program in C (Pyramid pattern program examples)