1 //
2 // C++ Interface: diskio (platform-independent components)
3 //
4 // Description: Class to handle low-level disk I/O for GPT fdisk
5 //
6 //
7 // Author: Rod Smith <rodsmith@rodsbooks.com>, (C) 2009
8 //
9 // Copyright: See COPYING file that comes with this distribution
10 //
11 //
12 // This program is copyright (c) 2009 by Roderick W. Smith. It is distributed
13 // under the terms of the GNU GPL version 2, as detailed in the COPYING file.
14 
15 #define __STDC_LIMIT_MACROS
16 #ifndef __STDC_CONSTANT_MACROS
17 #define __STDC_CONSTANT_MACROS
18 #endif
19 
20 #ifdef _WIN32
21 #include <windows.h>
22 #include <winioctl.h>
23 #define fstat64 fstat
24 #define stat64 stat
25 #define S_IRGRP 0
26 #define S_IROTH 0
27 #else
28 #include <sys/ioctl.h>
29 #endif
30 #include <string>
31 #include <stdint.h>
32 #include <errno.h>
33 #include <fcntl.h>
34 #include <sys/stat.h>
35 #include <iostream>
36 
37 #include "support.h"
38 #include "diskio.h"
39 //#include "gpt.h"
40 
41 using namespace std;
42 
43 DiskIO::DiskIO(void) {
44    userFilename = "";
45    realFilename = "";
46    modelName = "";
47    isOpen = 0;
48    openForWrite = 0;
49 } // constructor
50 
51 DiskIO::~DiskIO(void) {
52    Close();
53 } // destructor
54 
55 // Open a disk device for reading. Returns 1 on success, 0 on failure.
56 int DiskIO::OpenForRead(const string & filename) {
57    int shouldOpen = 1;
58 
59    if (isOpen) { // file is already open
60       if (((realFilename != filename) && (userFilename != filename)) || (openForWrite)) {
61          Close();
62       } else {
63          shouldOpen = 0;
64       } // if/else
65    } // if
66 
67    if (shouldOpen) {
68       userFilename = filename;
69       MakeRealName();
70       OpenForRead();
71    } // if
72 
73    return isOpen;
74 } // DiskIO::OpenForRead(string filename)
75 
76 // Open a disk for reading and writing by filename.
77 // Returns 1 on success, 0 on failure.
78 int DiskIO::OpenForWrite(const string & filename) {
79    int retval = 0;
80 
81    if ((isOpen) && (openForWrite) && ((filename == realFilename) || (filename == userFilename))) {
82       retval = 1;
83    } else {
84       userFilename = filename;
85       MakeRealName();
86       retval = OpenForWrite();
87       if (retval == 0) {
88          realFilename = userFilename = "";
89       } // if
90    } // if/else
91    return retval;
92 } // DiskIO::OpenForWrite(string filename)
93