从0开始学C++ 第二十二课:文件操作

本文介绍了C++中的文件流概念,包括使用ofstream、ifstream和fstream进行文件操作,展示了如何打开、关闭文件以及读写数据。重点讲解了文件操作在数据持久化中的应用,如保存配置信息和用户数据。通过实例演示了用户输入保存和读取文件的过程。
摘要由CSDN通过智能技术生成

第二十二课:文件操作

学习目标:

  • 理解文件流的概念。
  • 学习如何使用C++中的文件操作来读写数据。
  • 掌握使用fstream, ifstream, 和 ofstream 类进行文件操作。
  • 了解文件操作的常见用途。

学习内容:

  1. 文件流的概念:
    文件流是一种数据流,它从文件中读取数据或向文件中写入数据。在C++中,你可以通过包含头文件<fstream>来使用文件流。

  2. 打开和关闭文件:
    在C++中,可以使用ofstream(输出文件流)创建文件并向文件写入数据,使用ifstream(输入文件流)从文件读取数据,以及使用fstream(文件流)来同时进行读写操作。

    代码示例:

    #include <iostream>
    #include <fstream>
    using namespace std;
    
    int main() {
        // 写入文件
        ofstream outfile("example.txt");
        outfile << "This is an example text." << endl;
        outfile.close(); // 关闭文件流
    
        // 读取文件
        ifstream infile("example.txt");
        string line;
        if (infile.is_open()) {
            while (getline(infile, line)) {
                cout << line << '\n';
            }
            infile.close(); // 关闭文件流
        } else {
            cout << "Unable to open file";
        }
    
        return 0;
    }
    

    预计输出效果:

    This is an example text.
    
  3. 检查文件是否成功打开:
    使用is_open()方法可以检查文件是否成功打开。

  4. 文件操作的使用场景:
    文件操作通常用于数据持久化,例如保存程序的配置信息,存储用户生成的数据,或读取外部数据文件等。

练习题:

编写一个程序,它首先要求用户输入他们的名字和年龄。然后程序将这些信息保存到一个名为 “userinfo.txt” 的文件中。最后,程序读取这个文件,并将内容打印到控制台。

答案:

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main() {
    string name;
    int age;

    // 获取用户输入
    cout << "Enter your name: ";
    getline(cin, name);
    cout << "Enter your age: ";
    cin >> age;

    // 写入文件
    ofstream outfile("userinfo.txt");
    if (outfile.is_open()) {
        outfile << "Name: " << name << endl;
        outfile << "Age: " << age << endl;
        outfile.close();
        cout << "Information saved." << endl;
    } else {
        cout << "Unable to open file for writing." << endl;
    }

    // 读取文件
    ifstream infile("userinfo.txt");
    string line;
    if (infile.is_open()) {
        while (getline(infile, line)) {
            cout << line << '\n';
        }
        infile.close();
    } else {
        cout << "Unable to open file for reading." << endl;
    }

    return 0;
}

预计输出效果(示例):

Enter your name: John Doe
Enter your age: 30
Information saved.
Name: John Doe
Age: 30

在这个练习中,学生将学会如何获取用户输入,将数据写入文件,并从文件中读取数据。这些技能是文件处理和数据持久化的基础,并且是编程中常见的操作。

目录
第二十三课:C++标准库概述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值