BeginnersBook

  • Home
  • Java
    • Java OOPs
    • Java Collections
    • Java Examples
  • C
    • C Examples
  • C++
    • C++ Examples
  • DBMS
  • Computer Network
  • Python
    • Python Examples
  • More…
    • jQuery
    • Kotlin
    • WordPress
    • SEO
    • JSON
    • JSP
    • JSTL
    • Servlet
    • MongoDB
    • XML
    • Perl

C Program to Write a Sentence to a File

By Chaitanya Singh | Filed Under: C Programs

In this tutorial, you will learn how to write a C program to write a sentence to a file.

Program to write a sentence to a file

In this we are writing the a line entered by user into the mentioned file.

Variable fptr is a file pointer, since we want to write into the file, we are opening the file in writing mode. If fopen returns NULL, it means there is an error and file is not opened successfully. In this case, we are displaying an error message to the user and exiting the program.

If file opened successfully, we are reading the user input using fgets() function and writing into the file using fprintf() function. In the end we are closing the file using fclose() function.

#include <stdio.h>
#include <stdlib.h>

int main() {
  char ch[500];

  // File pointer
  FILE *fptr;

  // Open the file beginnersbook.txt in 'w' mode
  // Here 'w' represents the writing mode.
  fptr = fopen("beginnersbook.txt", "w");

  // If fptr is NULL then the file didn't open successfully
  if (fptr == NULL) {
    printf("Error! File cannot be opened");
    //exit the program
    exit(1);
  }
  printf("Enter sentence that you would like to write:\n");
  fgets(ch, sizeof(ch), stdin);
  fprintf(fptr, "%s", ch);
  fclose(fptr);
  return 0;
}

Output:
C Program to Write a Sentence to a File
File content after executing the program: The sentence entered by the user is successfully written to the file.
C Program to Write a Sentence to a File

Related C Examples:

  • C Program to read the first line from a file
  • C Program to print an integer entered by the user
  • C Program to print string using pointer
  • C Program to count vowels and consonants in a string using pointer
❮ C TutorialC Programs ❯

Programs

  • C Programs
  • Java Programs
  • C++ Programs

Copyright © 2012 – 2022 BeginnersBook . Privacy Policy . Sitemap