Google News
logo
C Program to Write a Sentence to a File
In the following example of C program to write a sentence to a file :
Program :
#include <stdio.h>
#include <stdlib.h>

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

“C” is a structured oriented programming language developed at “AT & T Bell Laboratories of USA” in 1972.  It was developed by Dennis Ritche in late 1970’s. It began to replace the more familiar languages of that time like PL/1, ALGOL etc. 
* 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.