Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

c++ file

作者:ー辈ふ只寵你人   发布日期:2026-03-05   浏览:49

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main() {
    // 创建一个ofstream对象,用于写入文件
    ofstream outfile;

    // 打开一个名为 "example.txt" 的文件,如果文件不存在则创建它
    outfile.open("example.txt");

    // 检查文件是否成功打开
    if (!outfile) {
        cout << "无法打开文件进行写入!" << endl;
        return 1;
    }

    // 写入一些文本到文件中
    outfile << "Hello, World!" << endl;

    // 关闭文件
    outfile.close();

    // 创建一个ifstream对象,用于读取文件
    ifstream infile;

    // 打开刚才创建的 "example.txt" 文件
    infile.open("example.txt");

    // 检查文件是否成功打开
    if (!infile) {
        cout << "无法打开文件进行读取!" << endl;
        return 1;
    }

    // 创建一个字符串变量,用于存储从文件中读取的内容
    string line;

    // 逐行读取文件内容并输出到控制台
    while (getline(infile, line)) {
        cout << line << endl;
    }

    // 关闭文件
    infile.close();

    return 0;
}

解释说明:

  1. 包含头文件#include <iostream>, #include <fstream>, #include <string> 引入了必要的库,以便我们可以使用输入输出流和字符串。
  2. 创建文件输出流对象ofstream outfile; 用于写入文件。
  3. 打开文件outfile.open("example.txt"); 打开或创建一个名为 example.txt 的文件。
  4. 检查文件是否成功打开:通过检查 outfile 是否为 false 来确保文件成功打开。
  5. 写入文件:使用 outfile << "Hello, World!" << endl; 将字符串写入文件。
  6. 关闭文件outfile.close(); 关闭文件以确保所有数据都被正确写入。
  7. 创建文件输入流对象ifstream infile; 用于读取文件。
  8. 打开文件infile.open("example.txt"); 打开之前创建的文件。
  9. 检查文件是否成功打开:通过检查 infile 是否为 false 来确保文件成功打开。
  10. 读取文件内容:使用 while (getline(infile, line)) 逐行读取文件内容,并将其输出到控制台。
  11. 关闭文件infile.close(); 关闭文件以释放资源。

上一篇:c++ multimap

下一篇:c++选择排序

大家都在看

c++闭包

c++向上取整的代码

c++单引号和双引号的区别

c++ 注释

c++如何判断素数

c++ functional

c++框架代码

c++格式化字符串

c++ orm框架

c++ string类

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站