文件流: ASCII 与 二进制

这里写图片描述

Ofstream: 输出文件流

  • ASCII 文本文件

    1. 一个字符一个字符的写

put(char ch);


#include <iostream>
#include <fstream>
#include <cstdlib>

using namespace std;

int main()
{
    int a[10];
    int i;

    //指定工作方式ios::out注意这是在定义类对象,文件流ofstream
    //ios::out 可以省略
    //ofstream outfile("out.dat",ios::out);
    ofstream outfile("file/out.dat");
    if(outfile==0)
    {
        cout<<"open error";
        exit(1);
    }

    for(i=0; i<10; i++)
    {
        cin>>a[i];
        outfile<<a[i] << " ";//注意输出流的对数据和字符的两种输出方式
        //outfile.put(a[i]);
    }

    outfile.close();

    return 0;
}


  • 二进制 字节文件
    write(const char *str, int num);
    下面的用write方法将字符串写进磁盘文件, 开始我还以为写进去的是文本呢!!

一个字符就使一个字节,所以即使是二进制文件你仍然能看的懂,不要以为写进去的就是文本了。
#include <fstream>
#include <iostream>
#include <cstdlib>
#include <cstring>

using namespace std;

struct Student
{
    char name[10];
    int age;
    double score;
};

int main()
{

    Student stu[3] = {
        "Larry",19,1000.1,
        "Ggeli",20,20000,
        "shun", 200, 3000,
    };

    //注意 这种方式能把文件放入指定的地方
    ofstream outfile("file/binary.dat", ios::out | ios::binary);
    if(!outfile)
    {
        cout << "error open" << endl;
        exit(1);
    }

    for(int i=0; i<3; i++)
    {
        for(int j=0; j<strlen(stu[i].name); j++)
            //outfile.put(stu[i].name[j]);
            outfile.write(&stu[i].name[j], 1);
    }

    outfile.close();

    return 0;
}

Ifstream: 输入文件流

注意存入文件中的数据是什么类型,最好用什么类型接收

#include <iostream>
#include <fstream>
#include <cstdlib>

using namespace std;

int main()
{
    int a[10];
    int i;

    ifstream infile("file/out.dat", ios::in);
    if(infile==0)
    {
        cout<<"open error";
        exit(1);
    }

    for(i=0; i<10; i++)
    {
        infile>>a[i];
    }

//  cout << a[1] << endl;

    infile.close();

    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值