C/C++ 读取文件指定行的内容

前几天在论坛里看帖子 发现一帖友提出的问题.如下是我给出来的相应实现

#include 
#include 
#include 

#define SET_ARRAY_ITEMS_ZERO(arrName) memset(arrName,0,sizeof(arrName))
#define FREE_MALLOC_PTR(ptrName); if(NULL!=ptrName){free(ptrName);ptrName=NULL;}
	
char* ReadSpeacialLine(char* filename, int whichLine);

int main(int argc, char* argv[])
{
	char *sdf = NULL;
	sdf = ReadSpeacialLine(argv[1], atoi(argv[2]));
	if(sdf)
	{
		printf("%s", sdf);
	}

	FREE_MALLOC_PTR(sdf); //此处必须有,因为在RSL函数里面分配了堆内存

	return 0;
}

char* ReadSpeacialLine(char* filename, int whichLine)
{
	if (whichLine < 0 || NULL == filename)
	{
		return NULL;
	}
	FILE *fp = fopen(filename, "r");
	if (NULL == fp) {
		return NULL;
	}
	int reachWhichLine = 0;
	int curLine = 1;
#define LINE_SIZE 256
	char *data = NULL;
	data = (char*) malloc(LINE_SIZE);
	while (!feof(fp))//文件未结束
	{
		memset(data, 0, LINE_SIZE);
		fgets(data, LINE_SIZE - 1, fp);
		curLine++;
		if (curLine > whichLine)
		{
			reachWhichLine = 1; //已经读取到whichLine行
			break;
		}
	}
	fclose(fp);

	return 0 == reachWhichLine ? NULL : data;
}

你可能感兴趣的:(C/C++ 读取文件指定行的内容)