c++文件操作

本文详细介绍了C++中进行文件操作的方法,包括打开、读取、写入和关闭文件的基本步骤,以及如何处理文件读写过程中的常见问题。通过实例代码,深入理解fstream库在文件操作中的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

#include <iostream>
#include <fstream>
using namespace std;
int main()
{

    //输入
    int a[10];
    ofstream outfile1("f1.dat"), outfile2("f2.dat");
    cout<<"输入5个数"<<endl;
    for(int i=0; i<5; i++)
    {
        cin>>a[i];
        outfile1<<a[i]<<" ";
    }
    cout<<"输入5个数"<<endl;
    for(int i=0; i<5; i++)
    {
        cin>>a[i];
        outfile2<<a[i]<<" ";
    }
    outfile1.close();
    outfile2.close();

    //放到f2后面
    {
        ifstream infile("f1.dat");
        ofstream outfile("f2.dat",ios::app);
        int k;
        for(int i=0; i<5; i++)
        {
            infile >> k;
            outfile<<k<<" ";
        }
        infile.close();
        outfile.close();
    }

    //输出f2
    {
        int b[10];
        ifstream infile("f2.dat");
        for(int i=0;i<10;i++)
        {
            infile >> b[i];
        }
        infile.close();
        for(int i=0;i<10;i++)
        {
            if(i==9) cout << b[i] << endl;
            else cout << b[i] << ' ';
        }
    }

    //排序
    {
        ifstream infile("f2.dat");
        int i,j,t;
        for(i=0; i<10; i++)
        {
            infile>>a[i];
        }
        for(i=0; i<9; i++)
        {
            for(j=0; j<9-i; j++)
            {
                if(a[j]>a[j+1])
                {
                    t=a[j];
                    a[j]=a[j+1];
                    a[j+1]=t;
                }
            }
        }
        infile.close();

        cout<<endl;
        ofstream outfile("f3.dat",ios::out);
        for( i=0; i<10; i++)
        {
            outfile<<a[i]<<" ";
            cout<<a[i]<<" ";
        }
        cout<<endl;
        outfile.close();
    }
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值