-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdisk.cc
77 lines (60 loc) · 1.62 KB
/
disk.cc
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
#include "disk.h"
#include <fstream>
#include <iostream>
#include <limits>
#include <mutex>
bool Disk::CreateDisk(const std::string& filePath)
{
std::ofstream newFile(filePath);
for (int i = 0; i != kNumOfSector * kSectorSize; ++i)
{
newFile.write("", 1); // one byte a time
}
return newFile.good();
}
Disk::Disk(const std::string& diskFile)
{
m_ioFile.open(diskFile, std::ios::in | std::ios::out | std::ios::binary);
}
Disk::~Disk()
{
m_ioFile.close();
}
bool Disk::isValid()
{
std::lock_guard<std::mutex> lock(m_mutex);
if (m_ioFile.good())
{
auto currentPos = m_ioFile.tellg();
m_ioFile.seekg(0, std::ios::beg);
m_ioFile.ignore(std::numeric_limits<std::streamsize>::max());
auto fileSize = m_ioFile.gcount();
m_ioFile.clear();
m_ioFile.seekg(currentPos);
return fileSize == kNumOfSector * kSectorSize;
}
else
{
return false;
}
}
bool Disk::read(char* buf, int sector)
{
std::lock_guard<std::mutex> lock(m_mutex);
m_ioFile.seekg(kSectorSize * sector, std::ios::beg);
m_ioFile.read(buf, kSectorSize);
return m_ioFile.gcount() == kSectorSize;
}
bool Disk::write(char* buf, int sector)
{
std::lock_guard<std::mutex> lock(m_mutex);
m_ioFile.seekp(kSectorSize * sector, std::ios::beg);
auto posBefore = m_ioFile.tellp();
m_ioFile.write(buf, kSectorSize);
auto posAfter = m_ioFile.tellp();
return posAfter - posBefore == kSectorSize;
}
bool Disk::sync()
{
return m_ioFile.sync() == 0; // NOTE: 这个地方似乎不支持用 clang 编译,clang-7.0.0 on Archlinux x64
}