Home > Backend Development > C++ > body text

How to write to a file using C++?

王林
Release: 2024-06-04 19:01:07
Original
458 people have browsed it

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");
Copy after login

This will create a file named myfile.txt and open it for writing.

Writing

To write to a file, use the << operator of the f object.

f << "Hello World" << endl;
Copy after login

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();
Copy after login

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;
}
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!