C++文件的读写

/主要采用iostream和fstream两个库来进行。其中fstream下面有ifstream表示读取文件打印到屏幕上,ostream表示将数据写到文件上。下面是一个案列:/

/*通过c++的iostream和fstream来读写文件*/
#include"stdio.h"
#include"iostream"
#include"fstream"
using namespace std;

int main()
{
    //声明一个对象来写数据
    ofstream outfile;
    //这里采用头文件fstream所包含的ofstream和ifstream
    //声明一个字符数组来存放数据
    char data[100];
//这里app代表append,如果不加则每次都重新建立文件,把前面的内容清空,app则在文件后面追加
    cout << "writing to the file..." << endl;
    cout << "please input your name:" << endl;
//  cin.getline(data, 100);  //获得输入的一行
//  cin >> data;

    int fun();
    outfile << fun() << endl;
//关闭文件,这个一定要记住
    outfile.close();


//读取文件并且输出
//声明读取对象infile,类型是ifstream
    ifstream infile;
    infile.open("cc_file.dat");
    cout << "reading the file now...." << endl;
    //读取文件所有行内容
    //for(int i=0;i<infile.)

    while(!infile.eof()){
    //把文件内容传给data
    infile >> data;
    cout << data << endl;
    }
    return 0;
}

//main()函数内部声明,函数外定义。
int fun() {
    int x, y;
    cout << "please input x:" << endl;
    cin >> x;
    cout << "please intpu y:" << endl;
    cin >> y;
    return x + y;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值