用VC实现一次性读取文件里全部内容。需要用到fseek和ftell函数。
feek函数:
原型:int fseek( FILE *stream, long offset, int origin )
作用:移动文件流的读写位置
包含头文件:#include <stdio.h>
参数:
返回值:当调用成功时则返回0,若有错误则返回-1。
第一个参数:stream为已打开的文件指针
第二个参数:offset为偏移量
第三个参数:origin设定从文件读写指针的哪里开始偏移,取值有:SEEK_SET、SEEK_CUR、 SEEK_END
SEEK_SET: 文件开头
SEEK_CUR: 当前位置
SEEK_END: 文件结尾
fseek函数一般用于二进制文件,也可以用于文本文件。用于文本文件操作时,需特别注意回车换行的情况:因为在一般在编辑器如UltraEdit中,回车换行视为两个字符0x0D和0x0A,但真实的文件读写和定位时却按照一个字符0x0A进行处理,因此碰到此类问题时,可以考虑将文件整个读入内存,然后在内存中手工插入0x0D的方法,这样可以达到较好的处理效果。
ftell函数:
原型: long ftell(FILE * stream)
作用:获取文件读写指针的当前位置
包含头文件:#include <stdio.h>
参数:stream为已打开的文件指针
返回值:成功则返回当前的读写位置,失败返回 -1。
代码如下:
#include <stdio.h>
#include <stdlib.h>
#include <string>
//一次性读取文件中的全部内容
std::string readfile(char * filename)
{
std::string content_str;
char * str_tmp;
FILE * f;
long length;
//以二进制形式打开文件
f = fopen(filename, "rb");
if (NULL == f)
{
printf("Open file fail\n");
return NULL;
}
//把文件的位置指针移到文件尾
fseek(f, 0, SEEK_END);
//获取文件长度;
length = ftell(f);
//把文件的位置指针移到文件开头
fseek(f, 0, SEEK_SET);
str_tmp = (char *)malloc((length + 1) * sizeof(char));
fread(str_tmp, 1, length, f);
str_tmp[length] = '\0';
fclose(f);
if(str_tmp)
{
content_str = str_tmp;
free(str_tmp);
str_tmp = NULL;
}
return content_str;
}
int main()
{
char * filename = "test.txt";
FILE * f;
f = fopen(filename, "wb");
if (NULL == f)
{
printf("Open file fail\n");
return -1;
}
//写文件
fprintf(f, "This is the first line.\nThis is the second line.\n");
fflush(f);
fclose(f);
std::string content_str = readfile(filename);
printf("%s\n",content_str.c_str());
return 0;
}