Write a Sentence to a File in C

Exercise:

Write a C Program to write a sentence to a file.

Click Here to View the Solution!
#include <stdio.h>
#include <stdlib.h>

int main() {
    char sentence[100];
    FILE *fptr;
    fptr = fopen("program.txt", "w");
    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;
}
Click Here to View the Output!
Enter a sentence:
This is a C programming 
Click Here to View the Explanation!
  • This program is used to write a string to a file.
  • In main(), a string array sentence is created with a size of 100.
  • A file pointer *fptr is created using the FILE type in order to work with files.
  • The file to which the sentence is to be is opened using the fopen function which takes the name of the file e.g. program.txt and the writing mode w as its arguments. If the file does not exist, the file will be created on opening.
  • A condition is set using the if statement that if fptr will be equal to NULL, an error message will be displayed, and the program will exit.
  • The program then requests the user to enter sentence and stores it in the variable sentence.
  • Finally, the function fprintf() function will be used to write the sentence to the file and the file will then be close using the fclose function.