codescracker


c++

C++ Program to Write to File



« Previous Program Next Program »


Write To File in C++

To write some content in a file using C++ programming, you have to enter the file name with extension to open that file using the function open(), then after opening the desired file, again ask to the user to enter some content (some line of text) to store in the file. And at last, close the file after use using the function close() as shown in the following program.

C++ Programming Code to Write Content to File

Following C++ program ask to the user to enter file name 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 line of text to store these lines inside the files for further use :

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

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

C++ program to write content to file

Here after writing four line of text that is :

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

Same Program in Other Language

You may like the same program in other programming languages:


« Previous Program Next Program »



Tools
Calculator

Quick Links
Signup - Login - Give Online Test