c语言获取文件第n行数据

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/localhostcom/article/details/80868301

运行环境:ubuntu 64bit

实现方法:使用fscanf偏移文件位置,再对文件进行读取。

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(int argc, char const *argv[])
{
	/* code */
	FILE *fin;
	char buf[1024];

	int x,y;
	int i;
	fin = fopen("/home/mycode/abc.txt","r");
	for(i = 0;i < 2;i++)
	{
		fscanf(fin,"%*[^\n]%*c");
		/******************************************************
			%*		:	是“跳过”
			[^\n]	        :	字符串的分隔符是"\n", 中括号里可以写 分隔符 表
			%*[^\n]         :	跳过 \n 前的所有字符串。
			%*c 	        :	是“跳过”行尾 的 换行符
		******************************************************/
	}
	//while((fgets(buf,1024,fin)) != NULL)
	#if 0
	//这里获取第3行到文件尾的数据
	while(fgets(buf,1024,fin))
	{
		printf("buf : %s\n", buf);
		memset(buf,0,1024);
	}
	#endif
	//这里只是获取第3行数据
	fgets(buf,1024,fin);
	printf("buf : %s\n",buf );
	fclose(fin);

	return 0;
}

结果如下:

猜你喜欢

转载自blog.csdn.net/localhostcom/article/details/80868301