主要代码
#include <fstream>
#include <iostream>
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) {
// 读文本文件
char* ch= new char[80];
char fname[255] = "a.txt";
ifstream in(fname); // 打开文件读
Memo1->Clear();
if (!in) {
Memo1->Lines->Add("文件打开失败!");
}
else {
while (in.getline(ch, 80)) // getline按行读取,返回流对象
Memo1->Lines->Add(ch); // 读入内容输出到Memo1
}
delete ch;
in.close();
}
// ---------------------------------------------------------------------------
struct STUDENT // 学生结构体
{
char strName[20]; // 姓名
int nGrade; // 成绩
};
void __fastcall TForm1::Button2Click(TObject *Sender) {
// 写文本文件
ofstream out;
out.open("a.txt"); // 打开或创建a.txt文本文件
STUDENT st1 = {"张 三", 90};
STUDENT st2 = {"李 四", 80};
// ----------把成绩信息存到文本文件---------------
out << st1.strName << "\t" << st1.nGrade << endl;
out << st2.strName << "\t" << st2.nGrade << endl;
out.close(); // 关闭文件
}
// ---------------------------------------------------------------------------
输出效果