Home  >  Article  >  Backend Development  >  How to write to a file using C++?

How to write to a file using C++?

王林
王林Original
2024-06-04 19:01:07473browse

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 to a file using C++?

#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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn