文件流: ASCII 与 二进制

文件流: ASCII 与 二进制_第1张图片

Ofstream: 输出文件流

  • ASCII 文本文件

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

put(char ch);


#include 
#include 
#include 

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<" ";//注意输出流的对数据和字符的两种输出方式
        //outfile.put(a[i]);
    }

    outfile.close();

    return 0;
}


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

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

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 
#include 
#include 

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;
}

你可能感兴趣的:(#,C++与C,学生时代笔记,ascii,ios,二进制)