In this tutorial, you will learn how to write a C program to write a sentence to a file.
Program to write a sentence to a file
In this we are writing the a line entered by user into the mentioned file.
Variable fptr
is a file pointer, since we want to write into the file, we are opening the file in writing mode. If fopen returns NULL, it means there is an error and file is not opened successfully. In this case, we are displaying an error message to the user and exiting the program.
If file opened successfully, we are reading the user input using fgets()
function and writing into the file using fprintf()
function. In the end we are closing the file using fclose()
function.
#include <stdio.h>
#include <stdlib.h>
int main() {
char ch[500];
// File pointer
FILE *fptr;
// Open the file beginnersbook.txt in 'w' mode
// Here 'w' represents the writing mode.
fptr = fopen("beginnersbook.txt", "w");
// If fptr is NULL then the file didn't open successfully
if (fptr == NULL) {
printf("Error! File cannot be opened");
//exit the program
exit(1);
}
printf("Enter sentence that you would like to write:\n");
fgets(ch, sizeof(ch), stdin);
fprintf(fptr, "%s", ch);
fclose(fptr);
return 0;
}
Output:
File content after executing the program: The sentence entered by the user is successfully written to the file.