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
|
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
struct ramfs_header {
unsigned int magic; //For error checking
unsigned int files;
};
struct ramfs_file_header {
unsigned int name_length;
unsigned int file_length;
};
#define INITRD_MAGIC 0x12379846
int main(int argc, char *argv[]) {
if (argc < 2) {
cerr << "Error : no output file specified." << endl;
cerr << "Usage : MakeRamFS <output.img> [<filename>:<ramfs filename> [...] ]" << endl;
return 1;
}
ofstream output(argv[1], ios::out | ios::binary);
ramfs_header hdr;
hdr.magic = INITRD_MAGIC;
hdr.files = argc - 2;
output.write((char*)&hdr, sizeof(ramfs_header));
for (int i = 2; i < argc; i++) {
string name(argv[i]);
string file;
while (!name.empty()) {
if (name[0] == ':') {
name = name.substr(1, name.size() - 1);
break;
}
file += name[0];
name = name.substr(1, name.size() - 1);
}
ramfs_file_header fhdr;
if (file == "") { //This is a directory
fhdr.name_length = name.size();
fhdr.file_length = 0; //File length of 0 means directory
output.write((char*)&fhdr, sizeof(ramfs_file_header));
output << name;
output << '\0';
continue;
}
ifstream infile(file.c_str(), ios::in | ios::binary);
if (!infile) {
fhdr.name_length = 0; //Name and length = 0 means invalid file
fhdr.file_length = 0;
output.write((char*)&fhdr, sizeof(ramfs_file_header));
continue;
}
fhdr.name_length = name.size();
fhdr.file_length = 0;
while (!infile.eof()) {
char c;
infile.read(&c, 1);
fhdr.file_length++;
}
infile.close(); infile.open(file.c_str(), ios::in | ios::binary); //Rewind file
output.write((char*)&fhdr, sizeof(ramfs_file_header));
output << name;
output << '\0';
char *c = new char[fhdr.file_length];
for (int i = 0; i < fhdr.file_length; i++) {
char ch;
infile.read(&ch, 1);
output.write(&ch, 1);
}
delete [] c;
infile.close();
}
output.close();
return 0;
}
|