Home > Backend Development > C++ > body text

How to read and write text files using C++?

王林
Release: 2024-06-04 13:54:13
Original
485 people have browsed it

To read and write text files in C++, you can use the fstream library. Specific steps: 1. Open the file: open the file in input mode (ifstream) for reading, open the file in output mode (ofstream) for writing or append writing. 2. Read the file: Use the operator>> operator to read the file content line by line. 3. Write to file: Use operator

How to read and write text files using C++?

Reading and writing text files using C++

Text files are a simple way to store data in human-readable text. In C++, text files can be read and written using the fstream library.

Open a text file

To open a text file, you can use ifstream (input file stream) or ofstream (output file stream) file stream) class. For example:

// 打开文件以进行读取
ifstream infile("input.txt");

// 打开文件以进行写入(覆盖现有文件)
ofstream outfile("output.txt");

// 打开文件以进行追加(在文件末尾写入)
ofstream outfile("output.txt", ios::app);
Copy after login

Read a text file

To read a text file, you can use the operator>> operator, for example:

string line;
while (getline(infile, line)) {
  // 处理文件中的每一行
}
Copy after login

Write a text file

To write a text file, you can use the operator<< operator, for example:

outfile << "Hello, world!" << endl;
Copy after login

Practical Case

The following program reads a text file and prints its contents:

#include <fstream>
#include <iostream>

using namespace std;

int main() {
  // 打开文件以进行读取
  ifstream infile("input.txt");

  // 读取文件内容
  string line;
  while (getline(infile, line)) {
    cout << line << endl;
  }

  return 0;
}
Copy after login

The above is the detailed content of How to read and write text files 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