文件的读与写操作

来源:互联网 发布:大数据集成平台 编辑:程序博客网 时间:2024/04/30 19:56

//文件的读与写操作.cpp

#include <iostream.h>
#include"fstream.h"
#include<stdlib.h>

#define SIZE 2

typedef struct{
 char name[10];
 int num;
 int age;
 char addr[15];
}STU;

STU stud[SIZE]={{"zhang",1001,13,"room1"},
    {"li",1002,23,"room2"}
    };

void main(void)
{
STU temp;
fstream fp("d://f1.txt",ios::out|ios::in|ios::binary);
if(fp.fail()){
 cout<<"cannot open file/n";
 exit(1);
 }

for(int i=0;i<SIZE;i++)
    fp.write((char*)&stud[i],sizeof(STU));

fp.seekg(sizeof(STU),ios::beg);//移动读指针,离其始位置sizeof(STU)字节
cout<<fp.tellg()<<endl;        //返回当前读指针的位置距流开始位置的字节数

fp.read((char*)&temp,sizeof(STU));
 cout<<temp.name<<"  "<<temp.num<<"  "<<
  temp.age<<"  "<<temp.addr<<endl;

fp.close();

}

原创粉丝点击