Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- point.h:
- #pragma once
- struct Point {
- double x, y, z;
- Point() : x(0.0), y(0.0), z(0.0) {}
- Point(double x, double y, double z) : x(x), y(y), z(z) {}
- };
- FileError.h:
- #pragma once
- enum FileError {
- SUCCESS,
- ACCESS_DENIED,
- OUT_OF_BOUNDS,
- FILE_INVALID
- };
- BinaryFile.h:
- #pragma once
- #include <string>
- #include <fstream>
- #include <vector>
- #include "FileError.h"
- #include "Point.h"
- using namespace std;
- class BinaryFile
- {
- private:
- fstream file;
- string path;
- int fileSize;
- fstream::openmode openMode;
- public:
- BinaryFile(const string path, fstream::openmode openMode);
- FileError Write(const vector<Point>& points);
- FileError Read(vector<Point>& points);
- FileError Read(Point& point, const int index);
- };
- main:
- #include <vector>
- #include "BinaryFile.h"
- #include "Point.h"
- using namespace std;
- int main()
- {
- BinaryFile binaryFile("test.bin", fstream::out | fstream::in | fstream::trunc);
- vector<Point> points;
- for (int i = 0; i < 5; i++)
- {
- Point point(i, i + 1.0, i + 2.0);
- points.push_back(point);
- }
- binaryFile.Write(points);
- }
- BinaryFile.cpp:
- #include "BinaryFile.h"
- BinaryFile::BinaryFile(const string path, fstream::openmode openMode)
- {
- this->path = path;
- //...
- this->openMode = openMode | fstream::binary;
- file.open(path, this->openMode);
- }
- FileError BinaryFile::Write(const vector<Point>& points)
- {
- if (!this->file.is_open())
- return FileError::FILE_INVALID;
- if (!(openMode & fstream::out))
- return FileError::ACCESS_DENIED;
- int bytes = points.size() * sizeof(Point);
- file.write((const char*)points.data(), bytes);
- return FileError::SUCCESS;
- }
- FileError BinaryFile::Read(vector<Point>& points)
- {
- if (!this->file.is_open())
- return FileError::FILE_INVALID;
- if (!(openMode & fstream::in))
- return FileError::ACCESS_DENIED;
- file.seekg(0, file.end);
- int bytes = file.tellg();
- file.seekg(0, file.beg);
- if (bytes <= 0)
- return FileError::OUT_OF_BOUNDS;
- int pointsCount = bytes / sizeof(Point);
- points = vector<Point>(pointsCount);
- file.read((char*)points.data(), bytes);
- return FileError::SUCCESS;
- }
- FileError BinaryFile::Read(Point& point, const int index)
- {
- return FileError();
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement