文件的讀與寫操作

//文件的讀與寫操作.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();

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章