c/c++文件操作

x33g5p2x  于2021-09-19 转载在 C/C++  
字(2.8k)|赞(0)|评价(0)|浏览(403)

文件的基本操作:

1.打开文件

File * fopen(char *fileURL,char *Mode); 文件路径 文件格式
	1.声明一个文件指针,接收fopen返回的文件指针
		File *fp;
	2.fopen打开文件
		fp=fopen("1.txt","读写方式");
		注意点:如果fp==NULL,说明打开文件失败
	路径:
		相对路径:同一个文件夹下
		绝对路径:明确的路径
	读写方式:
		w:write   写
		r:read    读
		a:append  追加
		+:        读,写
		b:binary  二进制
		注意:
			w:如果文件存在会清空文件,如果文件不存在会创建一个文件
			r:步具备创建功能,也不具备清空功能
			a:追加,不清空,在原文件后面接着写

2.读写文件

1.以字符方式读写
		fgetc() fputc()
	2.以字符串方式读写
		fgets() fputs()
	3.格式化读写
		fprintf() fscanf()
	4.结构化读写
		fread() fwrite()

3.关闭文件

文件操作一定要关闭文件
	fclose(File,*fp);

实现代码:

#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<iostream>
#include<string.h>
using namespace std;

struct boy {
	char name[15];
	char sex[15];
	int age;
};

int main() {

	//r和w的区别
	FILE* read;
	read = fopen("1.txt", "r"); //以读的方式打开文件

	if (read == NULL) {
		cout << "打开文件失败" << endl;
	}
	else {
		cout << "文件存在" << endl;
	}

	read = fopen("1.txt", "w"); //以写的方式打开文件,如果文件不存在会创建一个文件

	if (read == NULL) {
		cout << "打开文件失败" << endl;
	}
	else {
		cout << "文件存在" << endl;
	}

	fclose(read); //关闭文件

	cout << "-------------------" << endl;

//以字符的形式读写文件

	//字符的形式写文件
	FILE* fp = fopen("2.txt", "w"); //以写的方式打开文件
	char str[] = { "I love you" };
	for (int i = 0;i < strlen(str) + 1;i++) {
		fputc(str[i],fp);
	}
	fclose(fp);
	
	//字符的形式读文件
	fp = fopen("2.txt", "r");
	char value = fgetc(fp);
	while (value != EOF) {
		cout << value;
		value = fgetc(fp);
	}
	cout << endl;
	fclose(fp);

	cout << "-------------------" << endl;

//以字符串的形式读写文件

	//字符串的形式写入文件
	FILE* fps = fopen("2.txt", "w");//以写的方式打开文件
	fputs(str, fps);
	fclose(fps);

	//字符串的方式读文件
	fps = fopen("2.txt", "r");//以读的方式打开文件
	char strFile[1024];
	fgets(strFile, 1024,fps);
	puts(strFile);

	cout << "-------------------" << endl;

//格式化读写文件

	struct boy boys[3] = {
		{"li","nan",18},
		{"ming","nan",18},
		{"liu","nan",19}
	};

	//格式化写入文件
	FILE* fpg = fopen("3.txt", "w"); //以读的方式打开文件
	//fscanf,fprintf指定输入输出位置
	for (int i = 0;i < 3;i++) {
		fprintf(fpg,"%s\t%s\t%d\n", boys[i].name, boys[i].sex, boys[i].age);
	}
	fclose(fpg);

	//格式化读文件
	struct boy tboy;
	fpg = fopen("3.txt", "r");
	while (fscanf(fpg, "%s\t%s\t%d\n", &tboy.name, &tboy.sex, &tboy.age)!=EOF) {
		printf("%s\t%s\t%d\n", tboy.name, tboy.sex, tboy.age);
	}

	fclose(fpg);

	cout << "-----------------" << endl;

//结构化读写
//结构化方式读写的文件,文件里面是乱码

	//结构化写入文件
	FILE* write = fopen("4.txt", "w"); //以写的方式打开的文件
	fwrite(&boys[0], sizeof(struct boy), 3, write);
	fclose(write);

	//结构化读文件
	FILE* readfile = fopen("4.txt", "r"); //以读的方式打开文件
	struct boy tboys[3];
	fread(&tboys[0], sizeof(struct boy), 3, readfile);
	for (int i = 0;i < 3;i++) {
		printf("%s\t%s\t%d\n", tboys[i].name, tboys[i].sex, tboys[i].age);
	}
	fclose(readfile); //关闭文件指针

	return 0;
}

运行结果:

在这里插入图片描述

相关文章

微信公众号

最新文章

更多