C++ Programming Code Examples C++ > File Operations Code Examples C++ Programming Code to Write Content to File C++ Programming Code to Write Content to File 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. 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(); }