C++对二进制和文本文件操作练习

#文本文件

#include <iostream>
#include <fstream>

using namespace std;

int main()
{
    int a[10],max,i,order;
    ifstream infile("f1.dat",ios::in);
    {
        cout << "open error !" << endl;
        exit(1);
    }
    for (i=0;i<10;i++)
    {
        infile >> a[i];
        cout << a[i] << " ";
    }
    cout << endl;
    max=a[0];
    order=0;
    for (i=1;i<10;i++)
    {
        if(a[i]>max)
        {
            max=a[i];
            order=i;
        }
    }
    cout << "max=" << max << endl << "order=" << order << endl;
    infile.close();

    return 0;
} 

#二进制文件

#include <fstream>
#include <iostream>

using namespace std;

struct student
{
    int num;
    char name[20];
    float score;
};

int main()
{
    student stud[5]={1001,"Li",85,1002,"Fun",97.5,1004,"Wang",54,1006,"Tan",75.6,1010,"ling",96};
    fstream iofile("stud.dat",ios::in|ios::out|ios::binary);
    if(!iofile)
    {
        cerr << "open error !" << endl;
        abort();
    }
    for(int i=0;i<5;i++)
        iofile.write((char*)&stud[i],sizeof(stud[i]));
    student stud1[5];
    for (int i=0;i<5;i=i+2)
    {
        iofile.seekg(i*sizeof(stud1[i]),ios::beg);
        iofile.read((char*)&stud1[i/2],sizeof(stud1[i/2]));
        cout << stud1[i/2].num << " " << stud1[i/2].name << " " << stud1[i/2].score << endl;
    }
    cout << endl;
    stud[2].num=1012;
    strcpy(stud[2].name,"Wu");
    stud[2].score=60;
    iofile.seekp(2*sizeof(stud[0]),ios::beg);
    iofile.write((char*)&stud[2],sizeof(stud[2]));
    iofile.seekg(0,ios::beg);
    for(int i=0;i<5;i++)
    {
        iofile.read((char*)&stud[i],sizeof(stud[i]));
        cout << stud[i].num << " " << stud[i].name << " " << stud[i].score << endl;
    }
    iofile.close();

    return 0;
}
此条目发表在C++分类目录。将固定链接加入收藏夹。

发表评论

电子邮件地址不会被公开。 必填项已用*标注

To create code blocks or other preformatted text, indent by four spaces:

    This will be displayed in a monospaced font. The first four 
    spaces will be stripped off, but all other whitespace
    will be preserved.
    
    Markdown is turned off in code blocks:
     [This is not a link](http://example.com)

To create not a block, but an inline code span, use backticks:

Here is some inline `code`.

For more help see http://daringfireball.net/projects/markdown/syntax

Protected with IP Blacklist CloudIP Blacklist Cloud