C Program to Write a Sentence to a File
In this example, you’ll learn to write a sentence to a file using fprintf() statement.
This program stores a sentence entered by the user in a file.
#include <stdio.h>
#include <stdlib.h> /* For exit() function */
int main()
{
char sentence[1000];
FILE *fptr;
fptr = fopen("program.txt", "w");
if(fptr == NULL)
{
printf("Error!");
exit(1);
}
printf("Enter a sentence:\n");
gets(sentence);
fprintf(fptr,"%s", sentence);
fclose(fptr);
return 0;
}
Output
Enter sentence: I am awesome and so are files.
After the termination of this program, you can see a text file program.txt created in the same location where this program is located.
If you open and see the content, you can see the sentence: I am awesome and so are files.
In this program, a file is opened using opening mode “w”.
In this mode, if the file exists, its contents are overwritten and if the file does not exist, it will be created.
Then, the user is asked to enter a sentence. This sentence will be stored in file program.txt using fprintf()
function.
C program that writes a sentence to a file:
#include <stdio.h>
int main() {
FILE *fp;
char sentence[100] = "This is a sentence.";
fp = fopen("file.txt", "w");
if (fp) {
fprintf(fp, "%s", sentence);
printf("Sentence written to file.\n");
fclose(fp);
} else {
printf("Failed to open file.\n");
}
return 0;
}
Explanation:
#include <stdio.h>
includes the standard input-output header file in our program, which provides input and output operations functionality.int main()
is the entry point of our program.FILE *fp;
declares a file pointer variablefp
which will be used to open and write to the file.char sentence[100] = "This is a sentence.";
declares a character arraysentence
that contains the sentence that we want to write to the file.fp = fopen("file.txt", "w");
opens the file named “file.txt” in write mode and assigns the file pointer tofp
. If the file doesn’t exist, it will be created.if (fp) { ... }
checks if the file was opened successfully. If the file was opened successfully, the code inside the curly braces is executed, otherwise, it is skipped.fprintf(fp, "%s", sentence);
writes the sentence to the file usingfprintf()
. The%s
the format specifier is used to print a string.printf("Sentence written to file.\n");
prints a message to the console indicating that the sentence was successfully written to the file.fclose(fp);
closes the file.
When we compile and run this program, it will write the sentence “This is a sentence.” to the “file.txt” file.