-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfile.cpp
More file actions
122 lines (101 loc) · 2.2 KB
/
file.cpp
File metadata and controls
122 lines (101 loc) · 2.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
#include <stdio.h>
#include <string>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/mman.h>
#include "file.h"
using namespace std;
File::File()
{
filedata = NULL;
filelen = 0;
}
File::~File()
{
if(filedata != NULL)
{
free(filedata);
}
}
//读取文件
bool File::Read_File(string filename)
{
this->filename = filename;
FILE *fp = fopen(this->filename.c_str(), "r");
if(fp == NULL)
{
printf("File::Read_File(string filename): Read file fail!!! %m\n");
return false;
}
//将文件指针置于文件开头
rewind(fp);
fseek(fp, 0, SEEK_END);
//填写文件长度
filelen = ftell(fp);
//重置文件指针,置文件开头
rewind(fp);
//分配文件内存空间
filedata = (unsigned char *)malloc(filelen);
if(fread(filedata, 1, filelen, fp) == 0)
{
printf("File::Read_File(string filename): Read file to buffer fail!!! %m\n");
return false;
}
fclose(fp);
return 0;
}
//返回读取的文件的长度
int File::Get_filelen()
{
return filelen;
}
//返回文件的内容起始地址
unsigned char *File::Get_filedata()
{
return filedata;
}
//写文件
bool File::Write_File(string filename, unsigned char *filedata, int filelen)
{
this->filename = filename;
FILE *fp = fopen(this->filename.c_str(), "w");
if(fp == NULL)
{
printf("File::Write_File(): fail to open file !!! %m\n");
return false;
}
this->filedata = filedata;
this->filelen = filelen;
if(fwrite(this->filedata, 1, this->filelen, fp) == 0)
{
printf("File::Write_File(): fail to write file !!! %m\n");
return false;
}
fclose(fp);
return true;
}
bool File::Map_file_to_memory(string filename)
{
this->filename = filename;
int filefd = open(this->filename.c_str(), O_RDWR, 0);
this->filelen = lseek(filefd, 0, SEEK_END);
this->filedata = (unsigned char *)mmap(NULL, this->filelen, PROT_READ | PROT_WRITE, MAP_SHARED, filefd, 0);
close(filefd);
return true;
}
void File::Sync_memory_to_disk()
{
msync(this->filedata, this->filelen, MS_SYNC | MS_INVALIDATE);
}
void File::Unmap_file_from_memory()
{
munmap(this->filedata, this->filelen);
}
//删除文件
void File::Remove_file(string filename)
{
this->filename = filename;
remove(this->filename.c_str());
}