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
|
class file_byte_stream : public byte_stream_interface {
private:
#if defined(_MSC_VER) || defined(_WIN32)
HANDLE file_stream;
#else
FILE* file_stream;
#endif
// Opens the file and stores the file buffer handle in
// file_stream. If the open fails, an exception is thrown.
// If the open succeeds, file_stream is set to the FILE*
// associated with the file.
void open(const char* filename) {
#if defined(_MSC_VER) || defined(_WIN32)
file_stream = CreateFileA(filename,
GENERIC_READ,
FILE_SHARE_READ,
NULL,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
NULL);
if (file_stream == INVALID_HANDLE_VALUE) {
throw file_not_found
(message() << "In file_byte_stream, the file \"" << filename << "\" could not be opened",
filename);
}
//fopen(filename, "rb");
#else
file_stream = fopen(filename, "r");
if (!file_stream) {
throw file_not_found
(message() << "In file_byte_stream, the file \"" << filename << "\" could not be opened",
filename);
}
#endif
}
// Closes the file associated with file_stream. If
// file_stream is 0, close() does nothing.
void close() {
#if defined(_MSC_VER) || defined(_WIN32)
if (file_stream != INVALID_HANDLE_VALUE)
CloseHandle(file_stream);
#else
if (file_stream)
fclose(file_stream);
#endif
file_stream = 0;
}
public:
// Creates a byte stream given a file name.
file_byte_stream(const char* filename) : file_stream(0) { open(filename); }
// Creates a byte stream given a file name and memory allocator.
file_byte_stream(memory_allocator_interface&, const char* filename) : file_stream(0) {
open(filename);
}
// Resets the byte stream with a new file.
void reset(const char* filename) {
close();
open(filename);
}
// Reads <em>n</em> bytes from the byte stream, and stores
// them at <em>a</em>.
virtual size_t read(void* a, size_t n) {
#if defined(_MSC_VER) || defined(_WIN32)
DWORD bytes_read = 0;
ReadFile(file_stream, static_cast<char*>(a), DWORD (n), &bytes_read, NULL);
return bytes_read;
#else
return fread(static_cast<char*>(a), sizeof(char), n, file_stream);
#endif
}
// The virtual desctructor. Close the file stream owned by
// this object.
virtual ~file_byte_stream() {
close();
}
};
|