//#include "md5.h"
#include <iostream>
#include <malloc.h>
#include <memory.h>
#include <sys/time.h>
#include <stdio.h>
#include <time.h>
#include <cstdlib>
#include <sys/types.h>//这里提供类型pid_t和size_t的定义
#include <sys/stat.h>
#include <fcntl.h> // for open
#include <unistd.h> // for close
#include <string.h>
#include <stdlib.h>
#include <sys/mman.h>
using namespace std;
class file_operation
{
private:
int fd;
long size;
public:
char *data;
public:
file_operation():fd(-1),size(0),data(NULL)
{
std::cout << "fd=" << fd << " "<< "size="<< size << std::endl;
}
int openfile(std::string filepath)
{
fd = open(filepath.c_str(),O_RDWR |O_CREAT|O_APPEND ,0644);
if(fd <= 0)
return -1;
/*
* ftruncate()会将参数fd指定的文件大小改为参数length指定的大小。参数fd为已打开的文件描述词,而且必须是以写入模式打开的文件。
* ftruncate 必须执行在open 之后
* ftruncate(fd,20);
*/
size = lseek(fd, 0, SEEK_END);//读取文件内容实际长度
data = (char *) mmap( NULL, size ,PROT_READ | PROT_WRITE, MAP_SHARED , fd, 0 );
std::cout << "time : " << getDateTime() << std::endl;
std::cout << "fd=" << fd << " "<< "size="<< size << std::endl;
return 0;
}
/*
* 仅仅覆盖文件中写文件的长度
*/
int writefile(std::string context)
{
const char *buf = context.c_str();
if(size < strlen(buf))
return -1;
memcpy(data,buf,strlen(buf));
//只有在调用了munmap()后或者msync()时,才把内存中的相应内容写回磁盘文件,所写内容仍然不能超过文件的大小。
msync(data,strlen(buf),MS_SYNC|MS_INVALIDATE);
return 0;
}
/*
* 文件中全部填充为0
*/
void clearfile(void)
{
memset(data,0,size);
msync(data,size,MS_SYNC|MS_INVALIDATE);
}
void closefile(void)
{
munmap(data,size);
close(fd);
}
char* getDateTime()
{
static char nowtime[20];
memset(nowtime,0,20);
time_t rawtime;
struct tm* ltime;
time(&rawtime);
ltime = localtime(&rawtime);
strftime(nowtime, 20, "%Y-%m-%d %H:%M:%S", ltime);
return nowtime;
}
};
int main()
{
string filePath = "./test.yuv";
string md5_str = "42574129ec74f3f5df52e72396142b07";
string hashBuf;
file_operation File;
File.openfile(filePath);
std::cout << File.getDateTime() << std::endl;
hashBuf =(char*)(File.data);
#if 0
MD5 md5;
md5.update(hashBuf);
std::cout << md5.toString() << std::endl;
if ( md5.toString() == md5_str)
std::cout << "picture test success!" << std::endl;
md5.reset();
std::cout << File.getDateTime() << std::endl;
// File.clearfile();
File.writefile("22");
hashBuf =(char*)(File.data);;
md5.update(hashBuf);
std::cout << md5.toString() << std::endl;
#endif
File.closefile();
return 0;
}
C++ 文件操作封装成class
最新推荐文章于 2021-09-20 16:45:35 发布