C/C++ 文件與指針操作筆記


創建臨時文件

#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;
}

重命名文件

#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;
}

刪除文件

#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;
}

讀文件並輸出內容:

#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;
}

堆空間讀取

#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;
}

寫入內容到文件:

#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;
}

獲取文件總行數:

#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;
}

簡易文件加解密: 第一次調用文件實現加密,第二次調用實現解密.

#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;
}

實現格式化讀寫:

#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;
}

實現數組塊讀寫:

#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;
}

實現結構塊讀寫: 在定義結構塊的時候,不應使用指針變量,因為指正無法被轉儲到文件中.

#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;
}

實現結構隨機讀寫:

#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

#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;
}

實現小文件拷貝:

#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;
}

實現大文件拷貝:

#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;
}

實現文件合並:

#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;
}

實現統計文件大小:

#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

#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;
}

文件讀寫案例:

#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;
}



獲得文件有效行

#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;
}
#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;
}

文件讀取問題版

#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;
}

文件讀取 新建一個文本,里面有幾行數據,我們根據數組中的行數動態開辟內存空間,並且字符串長度是多長就分配多長的空間。

#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;
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM