Home  >  Article  >  Backend Development  >  How to read and write text files using C++?

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

王林
王林Original
2024-06-04 13:54:13422browse

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);

Read a text file

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

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

Write a text file

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

outfile << "Hello, world!" << endl;

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;
}

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!

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