Created
March 11, 2015 03:48
-
-
Save jroweboy/6d08999055a0df421879 to your computer and use it in GitHub Desktop.
file_io.cpp
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include "file_io.h" | |
#include <cstdio> | |
#ifdef _WIN64 | |
#include <io.h> | |
#include <fcntl.h> | |
#include <sys\stat.h> | |
#endif | |
size_t WriteBinaryFile(const std::string& filename, const void* buffer, const size_t buf_size) | |
{ | |
FILE* file = fopen(filename.c_str(), "wb"); | |
size_t size_written = fwrite(buffer, 1, buf_size, file); | |
fclose(file); | |
return size_written; | |
} | |
#ifdef _WIN64 | |
std::vector<u8> ReadBinaryFile(const std::string& filename) | |
{ | |
int fh, result; | |
unsigned int nbytes = BUFSIZ; | |
// Open a file | |
if (_sopen_s(&fh, filename.c_str(), _O_RDONLY, _SH_DENYRW, _S_IREAD) == 0) | |
{ | |
__int64 out_size = _filelengthi64(fh); | |
_close(fh); | |
std::vector<u8> file_buf(out_size); | |
FILE* bin_file = fopen(filename.c_str(), "rb"); | |
fread(&file_buf[0], 1, file_buf.size(), bin_file); | |
fclose(bin_file); | |
return file_buf; | |
} | |
}; | |
#else | |
std::vector<u8> ReadBinaryFile(const std::string& filename) | |
{ | |
FILE* bin_file = fopen(filename.c_str(), "rb"); | |
if (bin_file == nullptr) return {}; | |
fseek(bin_file, 0, SEEK_END); | |
size_t out_size = ftell(bin_file); | |
fseek(bin_file, 0, SEEK_SET); | |
std::vector<u8> file_buf(out_size); | |
fread(&file_buf[0], 1, file_buf.size(), bin_file); | |
fclose(bin_file); | |
return file_buf; | |
}; | |
#endif | |
std::string ReplaceExtension(const std::string& filename, const std::string& ext) { | |
std::string new_filename; | |
size_t dot_pos = filename.find_last_of('.'); | |
if (dot_pos != std::string::npos) | |
new_filename = filename.substr(0, dot_pos); | |
new_filename += '.' + ext; | |
return new_filename; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment