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

How to open a file using C++?

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOriginal
2024-06-02 17:08:00601browse

In C++, use the fstream header file and the ifstream or ofstream classes to open files. The specific steps are as follows: Open the file for reading operation: ifstream ifs("file name"); Open the file for writing operation: ofstream ofs("file name");

How to open a file using C++?

How Open file using C++?

Opening a file in C++ involves using the fstream header file and the ifstream or ofstream class. The following are the steps on how to open a file in C++:

Open a file for reading

ifstream ifs("input.txt");
if (ifs.is_open()) {
    // 文件已成功打开,可以读取数据
} else {
    // 文件打开失败,处理错误
}

Open a file for writing

ofstream ofs("output.txt");
if (ofs.is_open()) {
    // 文件已成功打开,可以写入数据
} else {
    // 文件打开失败,处理错误
}

Practical case: reading and writing files

#include <iostream>
#include <fstream>

using namespace std;

int main() {
    // 打开文件进行读操作
    ifstream ifs("input.txt");
    if (ifs.is_open()) {
        string line;
        while (getline(ifs, line)) {
            // 从文件中读取一行数据并处理它
            cout << line << endl;
        }
        ifs.close(); // 读取完成后关闭文件
    }

    // 打开文件进行写操作
    ofstream ofs("output.txt");
    if (ofs.is_open()) {
        ofs << "Hello, world!" << endl; // 将数据写入文件
        ofs.close(); // 写入完成后关闭文件
    }

    return 0;
}

In this example, input.txt is used to read data, while output.txt is used to write data.

The above is the detailed content of How to open 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