Program to write a text to a file

We will write a program in C that will accept a string from the user and write the string in a file. In this program, we will use fopen function in order to open a file. We will also use fputs function which will write a string to a file.

Below is the program:

#include<stdio.h>
#include<conio.h>
void main()
{
	char *str;
	FILE *fp;

	//Open the file in write mode
	fp = fopen("write.txt", "w");

	printf("Enter a string: ");
	gets(str);
        
        //write string in a file
	fputs(str, fp);
	getch();

}

C Programming is brought you by LearnCOnline.com

You may also like...

2 Responses

  1. Beins says:

    What are the functions gets() and getch() for?

    • learnconline says:

      gets() is the function used to accept the string and store it in a variable. getch() will wait for a user to hit any key from the keyboard. Once the key is hit, the program will proceed ahead with its execution

Leave a Reply

Your email address will not be published. Required fields are marked *

FREE C Cheatsheet - Speed Up Your C Programming.

FREE C Cheatsheet - Speed Up Your C Programming.

Download a 7-page free cheat sheet for easy and quick access to C Concepts, Snippets, and Syntax.

Thank you! Check you inbox and access your cheat-sheet