English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Comprehensive Collection of C Programming Examples
In this example, you will learn to write a sentence in a file using the fprintf() statement.
To understand this example, you should be familiar with the followingC Language ProgrammingTopic:
This program will store the user's input sentence in a file.
#include <stdio.h> #include <stdlib.h> int main() { char sentence[1000]; // Create a file pointer to handle the file FILE *fptr; //Open the file in write 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 result
Enter a sentence: C Programming is fun Here, a file named program.txt is created. The file will contain the text that C programming is fun.
In the program, the user input sentence is stored in the sentence variable.
Then, open the file namedprogram.txtfile. If the file does not exist, it will be created.
Finally, use the fprintf() function to write the user input string to this file and then close the file.