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 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 file for further use :

/* C++ Program - Write to File */
void main()
	ofstream fp;
	char s[100], fname[20];
	cout<<"Enter a file name with extension (like file.txt) to create a file : ";
		cout<<"Error in opening file..!!";
	cout<<"Enter few lines of text :\n";

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 »


Quick Links
Signup - Login - Give Online Test