C Program To Write A File

C programming allows to read or write files. In this program, a user will enter some text which will be stored in a file using file operations in C.


Learn C programming concepts, before you begin with this example.

Problem Definition

The program demonstrate the C language ability to write to file and it is achieved with the help of following C language features.

FILE – a file structure data type which is usually hidden from users.

fopen() – builtin function to open a file in buffer, so that you can read or write to file.


fprintf() – a print function to write to file from console.

fclose() – close the file and file pointer.

Program Source Code

Before you start executing the program, make sure you have created a file called demo.txt in the same directory where the program resides.

#include <stdio.h>
#include <stdlib.h>
int main()
    char c[1000];
    FILE *fptr;
    fptr = fopen("demo.txt","w");
    if(fptr == '\0')
    printf("Enter a Sentence:\n\n");
        fprintf(fptr,"%s", c);
    return 0;


When run the program, it will ask for a sentence from user as input. See the diagram below, type the sentence you want to write to the file and press enter.

Enter a Sentence:

OMG ! This is a big red horse.
Press any key to continue . . . 

You must go to the directory where the C program resides and open the file – demo.txt. The content of the console is written to the file successfully.

Output - Program to Write to a File
Output – Program to Write to a File


Ads Blocker Image Powered by Code Help Pro

Ads Blocker Detected!!!

We have detected that you are using extensions to block ads. Please support us by disabling these ads blocker.