Home > Article > Backend Development > How to write to a file using C++?
In C++, you can use the ofstream class to write a file, open the file through the open() method, write to the file using the
#How to write a file using C++?
Introduction
In C++, you can use the ofstream
class to write files. ofstream
The object represents an output stream that can be written to a file.
Syntax
ofstream f; f.open("myfile.txt");
This will create a file named myfile.txt
and open it for writing.
Writing
To write to a file, use the operator of the <code>f
object.
f << "Hello World" << endl;
This will write the "Hello World" string to the file, appending a newline character.
Close the file
After writing is completed, the file must be closed to release system resources.
f.close();
Practical case
The following is a simple example of writing "Hello World" to a file:
#include#include using namespace std; int main() { // 打开文件 ofstream f; f.open("myfile.txt"); // 写入文件 f << "Hello World" << endl; // 关闭文件 f.close(); return 0; }
The above is the detailed content of How to write to a file using C++?. For more information, please follow other related articles on the PHP Chinese website!