C Program to Write a Sentence to a File

In this example, you will learn to write a sentence in a file using fprintf() statement.

Limited time offer: Get 10 free Adobe Stock images.ADS VIA CARBON

To understand this example, you should have the knowledge of the following C programming topics:


This program stores a sentence entered by the user in a file.


#include #include int main() { char sentence[1000]; // creating file pointer to work with files FILE *fptr; // opening file in writing mode fptr = fopen("program.txt", "w"); // exiting program if (fptr == NULL) { printf("Error!"); exit(1); } printf("Enter a sentence:\n"); fgets(sentence, sizeof(sentence), stdin); fprintf(fptr, "%s", sentence); fclose(fptr); return 0; }

Output

Enter a sentence: C Programming is fun

Here, a file named program.txt is created. The file will contain C programming is fun text.

In the program, the sentence entered by the user is stored in the sentence variable.

Then, a file named program.txt is opened in writing mode. If the file does not exist, it will be created.

Finally, the string entered by the user will be written to this file using the fprintf() function and the file is closed.