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 user in a file.

  1. #include <stdio.h>
  2. #include <stdlib.h> /* For exit() function */
  3. int main()
  4. {
  5. char sentence[1000];
  6. FILE *fptr;
  7. fptr = fopen("program.txt", "w");
  8. if(fptr == NULL)
  9. {
  10. printf("Error!");
  11. exit(1);
  12. }
  13. printf("Enter a sentence:\n");
  14. gets(sentence);
  15. fprintf(fptr,"%s", sentence);
  16. fclose(fptr);
  17. return 0;
  18. }


Enter sentence: 
I am awesome and so are files.

After 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, user is asked to enter a sentence. This sentence will be stored in file program.txt using fprintf() function.