读写文本文件 C++ Builder示例

主要代码

#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(); // 关闭文件
}
// ---------------------------------------------------------------------------

输出效果

代码下载

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

幸运骄子

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值