codescracker


c

C Program to Write to File



« Previous Program Next Program »


Write to File in C

To write some content in a file in C programming, you have to first open that file using the function fopen(), now ask to the user to enter the content and start placing the content in the file, character by character, after doing this close the file using the function fclose()

C Programming Code to Write to File

Following C program ask to the user to enter the file name with extension to open (if file present inside the directory) or create (if file not present inside the directory), then ask to the user to enter some lines of text to store these lines inside the files for further use :

/* C Program - Write to File */
		
#include<stdio.h>
#include<conio.h>
#include<string.h>
#include<stdlib.h>
void main()
{
	clrscr();
	FILE *fp;
	char s[100], fname[20];
	printf("Enter a file name with extension (like file.txt) to create a file : ");
	gets(fname);
	fp=fopen(fname, "w");
	if(fp==NULL)
	{
		printf("Error in opening file..!!");
		getch();
		exit(1);
	}
	printf("\nEnter few lines of text :\n");
	while(strlen(gets(s))>0)
	{
		fputs(s, fp);
		fputs("\n",fp);
	}
	fclose(fp);
	getch();
}

When the above c program is compile and executed, it will produce the following result:

c program to write to file

Here after writing four line of text that is :

After writing the above four line you will press double enter (line break), your all the four line will be written in the file named file.txt and output screen backed to the program screen. Now go to the next program to know how to read this file and display its content on the screen.

Same Program in Other Programming Language

You may also like same program in other programming languages:


« Previous Program Next Program »



Tools
Calculator

Quick Links
Signup - Login - Give Online Test