C++文件IO操作的简单示例

本文提供两个C++程序示例,展示了如何使用标准库中的ifstream和ofstream类进行文件的复制操作。程序包括了输入输出文件名的交互提示,并记录了文件复制所花费的时间。

CppIODemo1.cpp

#include <iostream>
#include <fstream>
#include <chrono>
#define INPUT_BUFFER_SIZE 1024 * 1024
int main()
{
    using namespace std;
    cout << "Type an input file name: ";
    string filename;
    getline(cin, filename);
    ifstream ifs(filename, ifstream::in | ifstream::binary);
    if (ifs)
    {
        cout << "Type an output file name: ";
        getline(cin, filename);
        ofstream ofs(filename, ofstream::out | ofstream::binary);
        if (ofs)
        {
            cout << "Copying file..." << endl;
            char buffer[INPUT_BUFFER_SIZE];
            chrono::system_clock::time_point startTime = chrono::system_clock::now();
            while (!ifs.eof())
            {
                streamsize numberOfCharacters = ifs.read(buffer, INPUT_BUFFER_SIZE).gcount();
                ofs.write(buffer, numberOfCharacters);
            }
            chrono::system_clock::time_point endTime = chrono::system_clock::now();
            float elapsedTime = static_cast<chrono::duration<float, ratio<1, 1>>>(endTime - startTime).count();
            cout << "File copied, elapsed time: " << elapsedTime << endl;
        }
        else
            cerr << "Cannot open output file: '" << filename << "'!" << endl;
    }
    else
        cerr << "Cannot open input file: '" << filename << "'!" << endl;
    return 0;
}

 

CppIODemo2.cpp

#include <iostream>
#include <fstream>
#define INPUT_BUFFER_SIZE 1024 * 1024
int main()
{
    std::cout << "Enter an input file name: ";
    std::string filename;
    std::getline(std::cin, filename);
    std::ifstream ifs(filename, std::fstream::in);
    if (ifs.is_open())
    {
        std::cout << "Enter an output file name: ";
        std::getline(std::cin, filename);
        std::ofstream ofs(filename, std::fstream::out);
        if (ofs.is_open())
        {
            char buffer[INPUT_BUFFER_SIZE];
            while (!ifs.eof())
            {
                std::streamsize numberOfCharacters = ifs.read(buffer, INPUT_BUFFER_SIZE).gcount();
                std::cout.write(buffer, numberOfCharacters);
                ofs.write(buffer, numberOfCharacters);
            }
        }
        else
            std::cout << "Cannot open file: " << filename << std::endl;
    }
    else
        std::cout << "Cannot open file: " << filename << std::endl;
    return 0;
}

 

附带一句:http://en.cppreference.com,此站点为C/C++权威参考手册^_^若不习惯英文,可浏览此站点的中文版http://zh.cppreference.com

转载于:https://www.cnblogs.com/buyishi/p/9027214.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值