C 语言 二级指针操作文件 柔性数组使用

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef  struct  _info*  pInfo;

struct _info
{
	int line;
	int len;
	char data[0];
}info;


int getFileLine(FILE* fd)
{
	if (fd == NULL)
	{
		fprintf(stdout, "[%s]%d : get file line failed\r\n", __FILE__,__LINE__);
		return -1;
	}

	int num = 0;
	char buf[1024];
	while ((fgets(buf, 1024, fd)) != NULL)
	{
		num++;
	}

	// 注意文件指针的问题, 避免在计算文件的内容行数的时候, 计算为空.
	fseek(fd, 0, 0);
	return num;
}

int readFile(FILE *fd, int len, pInfo* pArray)
{
	if (fd == NULL || pArray == NULL || len <= 0)
	{
		return -1;
	}

	char buf[1024];
	int  line_len =0;
	int  index = 0;
	memset(buf, 0, 1024);
	while ((fgets(buf, 1024, fd)) != NULL)
	{
		int currentLen = 0;
		currentLen = strlen(buf) + 1;
		pInfo currentP = malloc(sizeof(info) + currentLen);
		currentP->len = strlen(buf);
		currentP->line = index;
		strcpy(currentP->data, buf);
		// append  to pArray;
		pArray[index] = currentP;
		index++;
		memset(buf, 0, 1024);
	}

	return 1;
}

void printFile(pInfo* pArray,int len)
{
	if (pArray == NULL)
	{
		return NULL;
	}

	pInfo  current = NULL;
	
	for (int i = 0; i < len; i++)
	{
		current = pArray[i];
		fprintf(stdout, " current %d line,current string len is:%d, current string is : %s", current->line,current->len,current->data);
	}

}

void freeNode(pInfo* pArray, int len)
{
	if(pArray == NULL || len  < 0)
	{
		return NULL;
	}


	for (int i=0;i<len;i++)
	{
		free(pArray[i]);
		pArray[i] = NULL;
	}

	free(pArray);
	pArray = NULL;
}





void test(const char* filename)
{
	if (filename == NULL)
	{
		return NULL;
	}

	FILE *fd = NULL;

	fd = fopen(filename,"r");
	if (fd == NULL)
	{
		return NULL;
	}

	int len = getFileLine(fd);
	if (len == -1)
	{
		return NULL;
	}


	pInfo* pArray = malloc(sizeof(pInfo)*len);
	if (pArray == NULL)
	{
		fprintf(stdout, "[%s]%d : malloc parray failed \r\n", __FILE__, __LINE__);
		return NULL;
	}

	int res = readFile(fd, len, pArray);
	if (res == -1)
	{
		fprintf(stdout, "[%s]%d : read file failed \r\n", __FILE__, __LINE__);
		return NULL;
	}

	// print;
	printFile(pArray, len);

	freeNode(pArray,len);

	pArray = NULL;
	if (pArray != NULL)
	{
		perror("parray is't empty\r\n");
	}
	else {
		perror("parray is empty\r\n");
	}
}



int main()
{

	const char* file = "./ReadMe.txt";
	test(file);

	return 0;
}

存在问题 :

如果读取的文件时中文时, 在console中输出是乱码.

 

 

转载于:https://my.oschina.net/u/1579560/blog/3051993

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值