前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >C/C++ 文件与指针操作笔记

C/C++ 文件与指针操作笔记

作者头像
微软技术分享
发布2022-12-28 17:07:22
8100
发布2022-12-28 17:07:22

创建临时文件

代码语言:javascript
复制
#include <stdio.h>

int main(int argc, char *argv[])
{
	FILE *temp;
	char c;
	if ((temp = tmpfile()) != NULL)
	{
		fputs("hello lyshark\n", temp); // 向临时文件中写入要求内容
	}
	rewind(temp);                       // 文件指针返回文件首
	while ((c = fgetc(temp)) != EOF)    // 读取临时文件中内容
		printf("%c", c);
	fclose(temp);
	return 0;
}

重命名文件

代码语言:javascript
复制
#include <stdio.h>

int Rename_File(char *src_name, char *dst_name)
{
	FILE *fp = fopen(src_name, "r");
	if (fp != NULL)
	{
		rename(src_name, dst_name);
		fclose(fp);
	}
	return 0;
}

int main(int argc, char* argv[])
{
	Rename_File("c:/aaaa.log", "c:/lysharrr.log");

	system("pause");
	return 0;
}

删除文件

代码语言:javascript
复制
#include <stdio.h>

int Delete_File(char *file_name)
{
	FILE *fp;

	if ((fp = fopen(file_name, "r")) != NULL)
		fclose(fp);
	remove(file_name);

	if ((fp = fopen(file_name, "r")) == NULL)
		return 1;
	return 0;
}

int main(int argc, char* argv[])
{
	Delete_File("c:/lyshark.log");

	system("pause");
	return 0;
}

读文件并输出内容:

代码语言:javascript
复制
#include <stdio.h>
#include <stdlib.h>

int Read_File(FILE *fp)
{
	if (fp == NULL)
		return 0;

	char ch;
	// while ((ch = fgetc(fp)) != EOF)
	while (!feof(fp))
	{
		ch = fgetc(fp);
		if (feof(fp))
			break;
		printf("%c", ch);
	}
}

int main(int argc, char* argv[])
{
	FILE *fp = fopen("c:/lyshark.log", "r");

	Read_File(fp);

	system("pause");
	return 0;
}

堆空间读取

代码语言:javascript
复制
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char* argv[])
{

	FILE *fp = fopen("c:/lyshark.log", "r");

	char *buffer = malloc(sizeof(char)* 1024);

	while (feof(fp) == 0)
	{
		memset(buffer, 0, 1024);
		fgets(buffer, 1024, fp);
		printf("%s", buffer);
	}

	system("pause");
	return 0;
}

写入内容到文件:

代码语言:javascript
复制
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int Write_File(char *path, char *msg)
{
	FILE *fp = fopen(path, "a+");
	if(fp== NULL) return -1;

	char ch, buffer[1024];

	int index = 0;
	while (msg[index] != '\0')
	{
		fputc(msg[index], fp);
		index++;
	}
	fclose(fp);
	return 1;
}

int main(int argc, char* argv[])
{
	for (int x = 0; x < 10; x++)
		Write_File("c:/lyshark.log", "hello lyshark\n");

	system("pause");
	return 0;
}

获取文件总行数:

代码语言:javascript
复制
#include <stdio.h>
#include <stdlib.h>

int Get_File_Line(FILE *fp)
{
	if (fp == NULL) return -1;

	char buffer[4096] = { 0 };
	int line = 0;

	while (fgets(buffer, 4096, fp) != NULL)
		++line;
	// 恢复指针起始位置
	fseek(fp, 0, SEEK_SET);
	return line + 1;
}

int main(int argc, char* argv[])
{
	FILE *fp = fopen("c:/lyshark.log", "r");

	int line = Get_File_Line(fp);

	printf("文件总行数: %d \n", line);


	system("pause");
	return 0;
}

简易文件加解密: 第一次调用文件实现加密,第二次调用实现解密.

代码语言:javascript
复制
#include <stdio.h>
#include <stdlib.h>

int encrypt(char *src_file, char *dst_file, char *passwd)
{
	FILE *fp_src = fopen(src_file, "rb");
	FILE *fp_dst = fopen(dst_file, "wb");

	if (fp_src == NULL || fp_dst == NULL)
		return - 1;
	char ch;

	while (!feof(fp_src))
	{
		ch = fgetc(fp_src);
		if (feof(fp_src))
			break;

		ch = ch ^ *(passwd);
		fputc(ch, fp_dst);
	}
	fclose(fp_src);
	fclose(fp_dst);
	return 1;
}

int main(int argc, char* argv[])
{
	int encode_ret = encrypt("c:/lyshark.log", "c:/encode.log", "1233");
	if (encode_ret == 1)
		printf("加密完成 \n");

	int decode_ret = encrypt("c:/encode.log", "c:/decode.log", "1233");
	if (decode_ret == 1)
		printf("解密完成 \n");

	system("pause");
	return 0;
}

实现格式化读写:

代码语言:javascript
复制
#include <stdio.h>

struct Student
{
	int uid;
	char name[20];
	int age;
};


void write()
{
	FILE *fp = fopen("c://ttt.log", "wt+");

	struct Student stu[3] = {
		{1001,"admin",22},
		{1002,"guest",33},
		{1003,"uroot",12},
	};

	// 将数据格式化输出到文本中保存
	for (int x = 0; x < 3; x++)
		fprintf(fp, "%d %s %d \n", stu[x].uid, stu[x].name, stu[x].age);
	fclose(fp);
}

void read()
{
	struct Student stu;

	FILE *fp = fopen("c://ttt.log", "r");

	while (fscanf(fp,"%d %s %d \n",&stu.uid,&stu.name,&stu.age) != EOF)
	{
		printf("UID: %d --> Name: %s --> Age: %d \n", stu.uid,stu.name,stu.age);
	}


	/*
	while (fgets(buffer, 1024, fp) != NULL)
	{
		sscanf(buffer,"%d %s %d \n", stu.uid, stu.name, stu.age);
		index++;
	}
	*/
}



int main(int argc, char* argv[])
{
	write();
	read();

	system("pause");
	return 0;
}

实现数组块读写:

代码语言:javascript
复制
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>

int main(int argc, char* argv[])
{
	int Array[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

	// 将数组写入到文件中保存
	FILE *write = fopen("c://list.log", "wb");
	fwrite(Array, sizeof(int), 10, write);
	fclose(write);

	// 从文件中读取数组元素
	FILE *read = fopen("c://list.log", "rb");

	int NewArray[10] = { 0 };
	int index = 0;

	while (!feof(read))
	{
		fread(&NewArray[index], sizeof(int), 1, read);
		index++;
	}
	fclose(read);

	// 循环打印出数组元素
	for (int x = 0; x < 10; x++)
		printf("%d \n", NewArray[x]);

	system("pause");
	return 0;
}

实现结构块读写: 在定义结构块的时候,不应使用指针变量,因为指正无法被转储到文件中.

代码语言:javascript
复制
#include <stdio.h>
#include <stdlib.h>

struct Student
{
	int uid;
	char name[30];
	int age;
};

// 保存结构到文件中
int Save_Struct(struct Student *ptr, int len)
{
	FILE *fp = fopen("c:/save.json", "wb");
	if (fp == NULL)
		return -1;

	for (int x = 0; x < len; x++)
	{
		fwrite(&ptr[x], sizeof(struct Student), 1, fp);
	}
	fclose(fp);
	return 0;
}

// 从文件中加载结构
int Load_Struct(struct Student *ptr)
{
	FILE *fp = fopen("c:/save.json", "rb");
	if (fp == NULL)
		return -1;

	int index = 0;

	while (!feof(fp))
	{
		fread(&ptr[index], sizeof(struct Student), 1, fp);
		index++;
	}
	fclose(fp);
	return 0;
}

int main(int argc, char* argv[])
{
	struct Student stu[3] = {
		{ 1001, "admin", 22 },
		{ 1002, "guest", 33 },
		{ 1003, "root", 12 },
	};

	Save_Struct(&stu, 3);  // 保存文件

	// 将输入读取到read_stu结构中
	struct Student read_stu[3];
	Load_Struct(&read_stu);

	for (int x = 0; x < 3; x++)
		printf("UID: %d --> Name: %s --> Age: %d \n", read_stu[x].uid, read_stu[x].name, read_stu[x].age);

	system("pause");
	return 0;
}

实现结构随机读写:

代码语言:javascript
复制
#include <stdio.h>

struct Student
{
	int uid;
	char name[20];
	int age;
};


int main(int argc, char* argv[])
{
	struct Student stu[3] = {
		{ 1001, "admin", 22 },
		{ 1002, "guest", 33 },
		{ 1003, "uroot", 12 },
	};

	FILE *fp = fopen("c://was.txt", "wb+");
	/*
	for (int x = 0; x < 3; x++)
		fprintf(fp, "%d %s %d \n", stu[x].uid, stu[x].name, stu[x].age);
	fclose(fp);
	*/

	// 随机读写的方式
	fwrite(stu, sizeof(struct Student), 3, fp);   // 写入三条数据
	fclose(fp);

	struct Student p;

	FILE *fp1 = fopen("c://was.txt", "rb+");

	fseek(fp, sizeof(struct Student), SEEK_SET);   // 移动文件指针

	fread(&p, sizeof(struct Student), 1, fp1);      // 读取数据

	printf("%d %s \n",p.uid,p.name);   // 输出


	system("pause");
	return 0;
}

简易vim

代码语言:javascript
复制
#include <stdio.h>

int main(int argc, char* argv[])
{
	FILE * fp = fopen("c:/aaa.txt", "w");
	if (fp == NULL)
		return -1;

	char buf[1024];
	while (1)
	{
		memset(buf, 0, 1024);
		fgets(buf, 1024, stdin);
		if (strncmp("exit()", buf, 6) == 0)
			break;

		int index = 0;
		while (buf[index] != '\0')
			fputc(buf[index++], fp);
	}

	fclose(fp);
	system("pause");
	return 0;
}

实现小文件拷贝:

代码语言:javascript
复制
#include <stdio.h>

int Copy_File(const char *src,const char *dst)
{
	FILE *src_file = fopen(src, "rb");
	FILE *dst_file = fopen(dst, "wb");

	if (src_file == NULL || dst_file == NULL)
		return - 1;

	char buffer;

	while (fread(&buffer,sizeof(char),1,src_file) != 0)
	{
		fwrite(&buffer, sizeof(char), 1, dst_file);
	}

	fcloseall();
	return 1;
}

int main(int argc, char * argv[])
{
	Copy_File("c:/lyshark.exe", "c:/www.exe");

	system("pause");
	return 0;
}

实现大文件拷贝:

代码语言:javascript
复制
#include <stdio.h>
#include <stdlib.h>

int Copy_File(const char *src, const char *dst)
{
	FILE *src_file = fopen(src, "rb");
	FILE *dst_file = fopen(dst, "wb");

	if (src_file == NULL || dst_file == NULL)
		return -1;

	char *buffer;

	buffer = (char *)malloc(sizeof(char)* 1024);
	memset(buffer, 0, 1024);

	while (fread(buffer, sizeof(char), 1024, src_file) != 0)
	{
		fwrite(buffer, sizeof(char), 1024, dst_file);
		memset(buffer, 0, 1024);
	}
	free(buffer);
	fcloseall();
	return 1;
}

int main(int argc, char * argv[])
{
	Copy_File("c:/www.exe", "c:/gt.exe");
	system("pause");
	return 0;
}

实现文件合并:

代码语言:javascript
复制
#include <stdio.h>

int Merge_File(const char *src, const char *dst)
{
	FILE *src_file = fopen(src, "r");
	FILE *dst_file = fopen(dst, "a+");

	if (src_file == NULL || dst_file == NULL)
		return -1;

	char buffer;
	fseek(dst_file, 0, SEEK_END);

	buffer = fgetc(src_file);
	while (!feof(src_file))
	{
		fputc(buffer, dst_file);
		buffer = fgetc(src_file);
	}
	fcloseall();
	return 1;
}

int main(int argc, char * argv[])
{
	Merge_File("c:/aaa.txt", "c:/bbb.txt");
	system("pause");
	return 0;
}

实现统计文件大小:

代码语言:javascript
复制
#include <stdio.h>

int Get_File_Size(const char *file_name)
{
	FILE *fp;
	long file_size;

	if (fp = fopen(file_name, "r"))
	{
		fseek(fp, 0, SEEK_END);
		file_size = ftell(fp);
		fcloseall();
		return file_size;
	}
	return 0;
}

int main(int argc, char * argv[])
{
	long ret = Get_File_Size("c:/lyshark.exe");

	printf("文件大小是: %d 字节 \n", ret/1024);
	system("pause");
	return 0;
}

大文件排序 001

代码语言:javascript
复制
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

void Random()
{
	srand((unsigned int)time(NULL));
	FILE *fp = fopen("c:/sp.txt", "w");
	if (!fp)
		return -1;

	for (int x = 0; x < 10000; x++)
	{
		fprintf(fp, "%d\n", rand() % 1000 + 1);
	}
	fcloseall();
}


int main(int argc, char * argv[])
{
	FILE *fp = fopen("c:/sp.txt", "r");
	if (!fp)
		return -1;

	
	int *ptr = (int *)malloc(sizeof(int)* 10000);

	// 读取数据,并放入堆空间中.
	for (int x = 0; x < 10000; x++)
		fscanf(fp, "%d\n", &ptr[x]);

	for (int x = 0; x < 10000; x++)
	{
		for (int y = 0; y < 10000 - x - 1; y++)
		{
			if (ptr[y] > ptr[y + 1])
			{
				int tmp = ptr[y];
				ptr[y] = ptr[y + 1];
				ptr[y + 1] = tmp;
			}
		}
	}

	fcloseall();

	// 排序完成后,开始写入数据
	FILE *fp1 = fopen("c:/sp.txt", "w");
	if (!fp1)
		return -1;

	for (int x = 0; x < 10000; x++)
		fprintf(fp1, "%d\n", ptr[x]);

	fcloseall();
	free(ptr);

	system("pause");
	return 0;
}

文件读写案例:

代码语言:javascript
复制
#include <stdio.h>
#include <stdlib.h>

// 配置文件数组
struct ConfigInfo
{
	char key[64];
	char val[128];
};


// 获得文件有效函数
int get_line_config(FILE *file)
{

}

// 加载配置文件
void loadFile(const char *file_path,char **fileData,int len)
{
	FILE *fp = fopen(file_path, "r");
	if (NULL == fp)
		return;
	
	// 按行读取
	int lines = get_line_config(fp);   // 获取文件行数

	char **tmp = malloc(sizeof(char *)*lines);  // 给每行开辟内存

	char buf[1024] = {0};
	int index = 0;
	while (fgets(buf,1024,fp) != NULL)
	{
		// 如果返回false 说明无效
		if (!isvalid_configFile(buf))
		{
			continue;
		}

		tmp[index++] = malloc(strlen(buf) + 1);
		strcpy(tmp[index++], buf);
		memset(buf, 0, 1024);
	}

	*fileData = tmp;
	*len = lines;
}





// 解析配置文件
void parseFile_configfile(char **fileData, int len, struct ConfigInfo ** info)
{

}
// 获取指定配置信息
void getInfo_Config(struct ConfigInfo *info)
{

}

// 判断行是否有效
void isvalid_configFile()
{

}



int main(int argc, char * argv[])
{


	system("pause");
	return 0;
}

获得文件有效行

代码语言:javascript
复制
#include <stdio.h>
#include <stdlib.h>

// 判断数据是否符合规则
int isvald(const char *buf)
{
	if (buf[0] == '#' || buf[0] == '\n' || strchr(buf, ':') == NULL)
		return 0;
	return 1;
}

// 获取有效行
int get_line(FILE *fp)
{
	char buffer[1024] = { 0 };
	int index = 0;

	while (fgets(buffer, 1024, fp) != NULL)
	{
		if (!isvald(buffer))
			continue;
		memset(buffer, 0, 1024);
		index++;
	}
	fseek(fp, 0, SEEK_SET);
	return index;
}

int main(int argc, char * argv[])
{
	FILE *fp = fopen("c:/conf.ini","r");
	int line = get_line(fp);      // 获取文件有效行
	printf("有效行: %d \n", line);
	system("pause");
	return 0;
}
代码语言:javascript
复制
#include <stdio.h>
#include <stdlib.h>

// 配置文件数组
struct ConfigInfo
{
	char key[64];
	char val[128];
};

// 判断数据是否符合规则
int isvald(const char *buf)
{
	if (buf[0] == '#' || buf[0] == '\n' || strchr(buf, ':') == NULL)
		return 0;
	return 1;
}

// 获取有效行
int get_line(FILE *fp)
{
	char buffer[1024] = { 0 };
	int index = 0;

	while (fgets(buffer, 1024, fp) != NULL)
	{
		if (!isvald(buffer))
			continue;
		memset(buffer, 0, 1024);
		index++;
	}
	fseek(fp, 0, SEEK_SET);
	return index;
}

// 加载有效行,到内存栈地址
void load(const char *path, char **data, int *len)
{
	FILE *fp = fopen(path, "r");

	int line = get_line(fp);      // 获取有效行
	char **tmp = malloc(sizeof(char *)* line);   // 给每行开辟空间

	char buf[1024] = { 0 };
	int index = 0;

	while (fgets(buf,1024,fp) != NULL)
	{
		if (!isvald(buf))
			continue;

		tmp[index] = malloc(strlen(buf) + 1);
		strcpy(tmp[index], buf);
		memset(buf, 0, 1024);
		++index;
	}

	*data = tmp;
	*len = line;
	fcloseall();
}

// 解析
char * parser(char **data, int len, struct ConfigInfo **info,char *key)
{
	struct ConfigInfo *my = malloc(sizeof(struct ConfigInfo) * len);
	memset(my, 0, sizeof(struct ConfigInfo) * len);

	for (int x = 0; x < len; x++)
	{
		char *pos = strchr(data[x], ':');

		strncpy(my[x].key, data[x], pos - data[x]);     // 拷贝key
		strncpy(my[x].val, pos+1 , strlen(pos+1) -1);   // 拷贝val

		printf("key: %s --> val: %s \n", my[x].key,my[x].val);

		if (strcmp(key, my[x].key) == 0)
			return my[x].val;
	}

	// 释放文件
	for (int y = 0; y < len; ++y)
	{
		if (data[y] != NULL)
			free(data[y]);
	}
}

int main(int argc, char * argv[])
{
	char *filedata = NULL;
	struct ConfigInfo *info = NULL;
	int lines = 0;

	load("c:/conf.ini", &filedata, &lines);

	char * user = parser(filedata, lines, &info,"username");

	printf("username = %s", user);


	system("pause");
	return 0;
}

文件读取问题版

代码语言:javascript
复制
#include <stdio.h>
#include <string.h>

int main(int argc, char* argv[])
{


	getchar();

	FILE *fp = fopen("c:/lyshark.log", "w");
	if (fp == NULL) return -1;

	char buffer[1024];

	while (1)
	{
		memset(buffer, 0, 1024);
		fgets(buffer, 1024, stdin);

		if (strcmp(buffer, "exit"))
			break;

		int index = 0;
		while (buffer[index] != '\0')
			fputc(buffer[index++],fp);
	}


	fclose(fp);


	system("pause");
	return 0;
}

文件读取 新建一个文本,里面有几行数据,我们根据数组中的行数动态开辟内存空间,并且字符串长度是多长就分配多长的空间。

代码语言:javascript
复制
#include <stdio.h>
#include <stdlib.h>

// 获取文件的总行数
int GetFileLine(FILE *fp)
{
	if (fp == NULL) return -1;

	char buf[1024] = { 0 };
	int line = 0;
	while (fgets(buf,1024,fp) != NULL)
	{
		++line;
	}
	// 恢复指针起始位置
	fseek(fp,0,SEEK_SET);
	return line;
}

int ReadFileData(FILE *fp,int line,char **pContent)
{
	char buf[1024] = { 0 };
	int index = 0;
	
	while (fgets(buf, 1024, fp) != NULL)
	{
		int curLineLen = strlen(buf) + 1;    // 获取每行数据长度
		//printf("读取到每行数据: %s", buf);
		// 给当前行分配内存
		char * lineContent = malloc(sizeof(char)* curLineLen);

		strcpy(lineContent, buf);
		pContent[index++] == lineContent;

		memset(buf, 0, 1024);
	}
}

void ShowFileContent(char **pContent, int line)
{
	for (int i = 0; i < line; i++)
	{
		printf("%d %s", i, pContent[i]);
	}
}

int main(int argc, char* argv[])
{

	FILE *fp = fopen("c:/Recovery.txt", "r");
	int line = GetFileLine(fp);
	// 分配的行数取决于文件行数
	char **pContent = malloc(sizeof(char*)* line);

	// 读取文件内容
	ReadFileData(fp, line, pContent);

	// 输出文件内容
	ShowFileContent(pContent, line);

	system("pause");
	return 0;
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2020-05-11,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档