主要代码
#include <iostream>
#include <fstream>
using namespace std;
#include <vcl.h>
#pragma hdrstop
#include "Unit1.h"
// ---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
TForm1 *Form1;
// ---------------------------------------------------------------------------
__fastcall TForm1::TForm1(TComponent* Owner) : TForm(Owner) {
}
// ---------------------------------------------------------------------------
void __fastcall TForm1::Button1Click(TObject *Sender) {
Memo1->Text = "文件的随机读写 C++ Builder示例";
int n[10] = {0, 1, 2, 3, 4, 5, 9, 7, 8, 9};
register int i;
char fname[] = "a.dat";
ofstream out;
out.open(fname, ios::out | ios::binary);
if (!out) {
Memo1->Lines->Add("文件打开失败!");
}
out.write((char *)&n, sizeof n);
Memo1->Lines->Add("文件指针移到:");
out.seekp(6*sizeof(int)); // tellp()与tellg() 指针当前位置
Memo1->Lines->Add((UnicodeString)out.tellp());
out.put(6); // 把上面中间的9改成6
out.close();
for (i = 0; i < 10; i++) {
n[i] = 0;
}
ifstream in;
in.open(fname, ios::in | ios::binary);
if (!in) {
Memo1->Lines->Add("文件打开失败!");
}
in.read((char *)&n, sizeof n);
UnicodeString s;
for (i = 0; i < 10; i++) {
s = s + " " + IntToStr(n[i]);
}
Memo1->Lines->Add(s);
}
// ---------------------------------------------------------------------------
输出效果