In this tutorial you will learn about the C Program to Write Content to File and its application with practical example.
C Program to Write Content to File
In this tutorial, you will learn about the C Program to Write Content to File with a practical example.
Prerequisites
Before starting with this tutorial we assume that you are best aware of the following C programming topics:
- Operators in C Programming.
- Basic Input and Output function in C Programming.
- Basic C programming.
- Conditional Statements in C programming.
- Using file functions of c language.
Program to Write Content to File.
As we all know the file is a collection of characters, integers, and many data types. In strings, only one variable is declared which can store multiple values. First will take the file from the user. Then will Check that file if it’s empty or not. The C programming language has many pre-defined functions for file manipulation. but in today’s tutorial, Write Content to File from the user.
With the help of the below program, we can Write Content to File.
Algorithm:-
1 2 3 4 5 6 7 8 9 10 11 |
1. Declaring the variables for the program. 2. Opening the file in write mode. 3. Taking the string input from the user 4. Adding the string to the file. 5. Printing the results. 6. End program. |
Program to Write Content to File:-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
/* C Program to Write Content to File */ #include <stdio.h> #include <stdlib.h> int main() { //declairing the variable for the program 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); } //Taking the string from user to be inserted in the file printf("Enter a sentence:\n"); //Adding that string to the file and closing the file fgets(sentence, sizeof(sentence), stdin); fprintf(fptr, "%s", sentence); fclose(fptr); return 0; } |
Output:-
In the above program, we have first initialized the required variable.
- *fptr = it will hold the address value.
- sentence[1000] = it will hold the string data.
opening the file in write mod.
If the pointer is null then exit.
Taking the input sting from the user.