002_C++与C读写文件

本文介绍了使用C和C++进行文件读写的两种不同方法。C语言通过fopen、fprintf等函数操作文件,而C++则利用ifstream和ofstream类实现文件的读取和写入。文中提供了具体的代码示例来展示这两种语言中文件操作的基本流程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、c读写文件

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>


void test1() {
	//创建一个文件指针
	FILE* fp = NULL;
	//打开该文件
	fp = fopen("./test.txt", "w+");

	//将内容写入到文件中
	fprintf(fp, "姓名:汪汪汪\n");
	fputs("年龄:54\n", fp);

	fclose(fp);
}

void test2() {
	//创建一个文件指针
	FILE* fp = NULL;
	//定义一个缓冲区
	char buff[1024];

	//打开文件
	fp = fopen("./test.txt","r");
	//方法1
	/*fscanf(fp,"%s",buff);
	printf("%s\n",buff);*/

	while (fgets(buff,1024,fp)!=NULL) {
		printf("%s",buff);
	}

	//关闭文件
	fclose(fp);
}

int main() {
	test2();
	system("pause");
	return 0;
}

二、c++读写文件

#include<iostream>
using namespace std;
#include<fstream>

void test01() {
	ofstream ofs("./test.txt",ios::out|ios::trunc);
	if (!ofs.is_open()) {
		cout << "文件打开失败" << endl;
		return;
	}

	//写文件
	ofs << "姓名:哇哈哈" << endl;
	ofs << "年龄:33" << endl;
	ofs.close();
}

void test02() {
	ifstream ifs("./test.txt",ios::in);
	if (!ifs) {
		cout << "文件打开失败" << endl;
		return;
	}

	//方式1
	//char buf[1024] = { 0 };
	//while (ifs>>buf)
	//{	
	//	cout << buf << endl;
	//}

	//方式2
	char buf[1024] = {0};
	while (!ifs.eof()) {
		ifs.getline(buf,sizeof(buf));
		cout << buf << endl;
	}

	//方式3
	char c;
	while ((c=ifs.get())!=EOF) {
		cout << c;
	}

	ifs.close();
}

int main() {
	test02();
	system("pause");
	return EXIT_SUCCESS;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值