1、如下代码可实现对文件大小得读取,并读取特定长度存取到特定位置。其中seekg可以移动文件流得其实位置,进而从不同位置读取不同长度得数据。
std::ifstream t;
int length;
t.open(strFileName.c_str()); // open input file
t.seekg(0, std::ios::end); // go to the end
length = t.tellg(); // report location (this is the length)
t.seekg(0, std::ios::beg); // go back to the beginning
char *buffer = new char[length]; // allocate memory for a buffer of appropriate dimension
t.read(buffer, length); // read the whole file into the buffer
t.close(); // close file handle
2、判断文件是否存在
//通过读看文件是否存在
FILE *pf = fopen(fileName, "r");
if (NULL == pf)
{
return FALSE;
}
else
{
fclose(pf);
return TRUE;
}
//判断文件是否存在另一种方式
if((access(fileName,F_OK))!=-1)
{
printf("file not exist.\n");
return;
}
3、从文件A中读取数据进行加解密后写入B文件中,类似文件加解密操作(代码直接拷贝需要修改)
#define BUFFER_SIZE 1024
char buffer[BUFFER_SIZE];
bzero(buffer, sizeof(buffer));
int file_block_length = 0;
FILE *fpIn = fopen(fileName,"rb");
if(fpIn==NULL)
{
return false;
}
FILE *fpOut = fopen(newFileName,"wb");
if(fpOut==NULL)
{
fclose(fpIn);
return false;
}
while((file_block_length = fread(buffer, sizeof(char), BUFFER_SIZE, fpIn)) > 0)
{
fwrite(buffer,sizeof(char),file_block_length,fpOut);
}
fclose(fpIn);
fclose(fpOut);
5、类似1的功能实现读取文件大小读取文件内容等的操作。
char *buffer;
FILE *pf = fopen(szCertPath, "r");
if (NULL == pf)
{
return FALSE;
}
fseek(pf, 0, SEEK_END);
long length = ftell(pf);
buffer = (char *)malloc(length + 4);
memcpy(buffer, &length, 4);
rewind(pf);
fread(buffer + 4, sizeof(char), length, pf);