C读取文件(记事本能正常打开)

C读取文件(记事本能正常打开)

  • 下面这份代码是以二进制形式打开并且按行读取,读取成功后将数据存放到char*的buffer中,以便于使用,当然如果你要是在C++中使用,可以如下直接将其给到一个string中,这样用起来就更加方便。
	FILE * pFile;
	long long len;
	char *pbuf = NULL;
	string str;

	//read file
	pFile = fopen(filename, "rb");
	if (pFile == NULL)
	{
		perror("Open file error");
	}
	else
	{
		//read all data in buf
		fseek(pFile, 0, SEEK_END);
		len = ftell(pFile);
		fseek(pFile, 0, SEEK_SET);
		//apply memory
		pbuf = (char *)malloc(len + 1);
		memset(pbuf, 0, len + 1);//initialize pbuf
		fread(pbuf, len, 1, pFile);//read and display data
		//printf("show: %s.\n", pbuf);
		//printf("file.txt 的总大小 = %d 字节\n", len);
		str = pbuf;
	}
	//close file
	fclose(pFile);


发布了84 篇原创文章 · 获赞 63 · 访问量 9万+

猜你喜欢

转载自blog.csdn.net/wsq119/article/details/103952485