C++学习之文件操作

文章介绍了C++中使用fstream库进行文件操作的基本步骤,包括创建输入/输出对象,打开和关闭文件,以及如何向文件写入和从文件读取数据。示例代码展示了如何写入和读取文本数据,以及如何复制一个文件到另一个文件。
摘要由CSDN通过智能技术生成
  1. C++中定义了关于文件操作的标准库fstream,其内部定义了三个数据类型:

  1. 文件操作的基本步骤:创建输入/输出对象;对象调用函数打开文件;对文件进行操作;关闭文件。

  1. 文件操作的例子:

/*C++文件读写练习*/
#include <iostream>
#include <fstream>    //C++中的文件类,内部有文件类型的数据和操作函数
using namespace std;
//资料网站:https://www.runoob.com/cplusplus/cpp-files-streams.html;

/*向文件中写入、读取数据函数*/
void file_oprete(void)
{
    char data[100];
    /*向文件中写入数据:*/
    ofstream outfile;    //创建文件输出流对象
    outfile.open("test.txt");    //调用函数打开文件,如果没有此文件,则创建
    cout << "Wirte to the file" << endl;
    cout << "Enter your name:" << endl;
    cin.getline(data, 100);    //将输入存储到data数组中,数组大小为100;
    outfile << data << endl;        //将data数据输出到文件outfile中
    cout << "Enter your age:" << endl;
    cin >> data;
    cin.ignore();    //ignore函数可以忽略之前读语句留下的多余字符
    outfile << data << endl;
    outfile.close();        //关闭文件

    /*从文件中读数据*/
    ifstream infile;        //创建文件输入流对象
    infile.open("test.txt");        //打开文件
    cout << "Read from the file" << endl;
    infile >> data;    //将infile中的数据读到data中,读取一行。
    //infile >> data;
    cout << "读取的文件1:" <<data<< endl;
    infile >> data;    //接着上次的读取,读取文件的第二行数据
    cout << "读取的文件2:" << data << endl;
    infile.close();
}

/*将数据从一个文件复制到另一个文件*/
void file_copy(void)
{
    char data[100];
    ifstream infile;        //创建文件输入流对象,将文件中的数据输出
    ofstream outfile;    //创建文件输出流对象,将数据输出到文件中
    infile.open("test.txt");        //打开文件
    outfile.open("test1.txt");
    cout << "Copy from test.txt to test1.txt:" << endl;
    while (!infile.eof())
    {
        infile >> data;    //将数据输入到data中
        cout << data << endl;
        outfile << data << endl;        //将data中的数据输出到outfile中
    }
    infile.close();    //关闭文件
    outfile.close();
}

int main()
{
    /*测试函数:*/
    file_oprete();    
    file_copy();
    return 0;
}
  1. 总结:关于C++文件操作的问题,主要是理解文件的输入/输出和iostream流中'cin>>'/'cout<<'之间的异同。当向文件中写入数据时:data>>file;是将data中的数据输出到file中。当读取文件中的数据时:file>>data;是将file中的数据输入到data中。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值