C/C++文件操作

 一、文本文件操作

简单的写文件操作:只向文件中写入,不会打印在屏幕上。

步骤:包含头文件,创建流对象,指定打开方式,写入内容,关闭文件。

#include <iostream>
using namespace std;
#include <fstream>
void test01(){
	ofstream ofs;
	ofs.open("test.txt", ios::out);
	ofs << "张三" << endl;
	ofs.close();
}
int main() {
	test01;
}

查看文件所在路径,此种方式创建出的文本文件与项目在同一路径下。

1、写文件操作

代码

#include<fstream>
#include<iostream>

int main() {

	ofstream outfile("Student.txt", ios::out);
	if (!outfile) {
		cout << "文件写入失败" << endl;
		exit(0); //程序终止
	}
	cout << "文件写入成功";
	outfile << "张三" << endl;
	outfile.close();
}

运行结果 

 可以看到成功在记事本上建了一个Student的文本文件,并写下张三。

2、读文件操作

读取一个名为 Student.txt 的文件,并输出文件中的内容。

代码:

int main() {

	ifstream infile("Student.txt", ios::in);
	if (!infile.is_open()) {
		cout << "文件打开失败";
		exit(0);
	}
	string name;
	// name 是用来存储从文件中读取的字符串数据的变量
	cout << "文件打开成功"<<endl;
	infile  >>name;
	cout << name;
}

运行结果: 

 二、二进制文件操作

1、写文件操作

代码:

#include<fstream>
#include<iostream>

class Student {
public:
	char Stu_name[64];//最好不要用c++的string,会出现一些问题
	int  Stu_age;
};
int main() {

	ofstream outfile("Student1.txt", ios::out|ios::binary);
	if (!outfile) {
		cout << "文件写入失败" << endl;

	}
	cout << "文件写入成功" << endl;
	Student stu = { "张三",18 };
	outfile.write((char*)&stu, sizeof(Student));
	outfile.close();

}

 运行结果:

 2、读文件操作

代码:

#include<fstream>
#include<iostream>

class Student {
public:
	char Stu_name[64];//最好不要用c++的string,会出现一些问题
	int  Stu_age;
};
int main() {

	ifstream infile("Student1.txt", ios::in|ios::binary);
	if (!infile) {
		cout << "文件读取失败" << endl;
		exit(0);
	}
	cout << "文件读取成功" << endl;
	Student stu;
	infile.read((char*)&stu, sizeof(Student));
	cout << "姓名:" << stu.Stu_name << endl;
	infile.close();

}

运行结果:

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Zik----

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

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

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

打赏作者

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

抵扣说明:

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

余额充值