通常我会使用C样式文件IO,但我正在尝试一种现代C++方法,包括使用C++ 17特定的功能std::byte和std::filesystem.
将整个文件读入内存,传统方法:
#include <stdio.h>
#include <stdlib.h>
char *readFileData(char *path)
{
FILE *f;
struct stat fs;
char *buf;
stat(path, &fs);
buf = (char *)malloc(fs.st_size);
f = fopen(path, "rb");
fread(buf, fs.st_size, 1, f);
fclose(f);
return buf;
}
Run Code Online (Sandbox Code Playgroud)
将整个文件读入内存,现代方法:
#include <filesystem>
#include <fstream>
#include <string>
using namespace std;
using namespace std::filesystem;
auto readFileData(string path)
{
auto fileSize = file_size(path);
auto buf = make_unique<byte[]>(fileSize);
basic_ifstream<byte> ifs(path, ios::binary);
ifs.read(buf.get(), fileSize);
return buf;
}
Run Code Online (Sandbox Code Playgroud)
这看起来对吗?这可以改善吗?
我个人更喜欢std::vector<std::byte>使用,std::string除非您正在阅读实际的文本文档.问题make_unique<byte[]>(fileSize);在于您立即丢失数据的大小并且必须在单独的变量中携带它.它可能比std::vector<std::byte>给定的快一小部分,它不会初始化为零.但我认为这可能总是被读取磁盘所花费的时间所掩盖.
所以对于二进制文件,我使用这样的东西:
std::vector<std::byte> load_file(std::string const& filepath)
{
std::ifstream ifs(filepath, std::ios::binary|std::ios::ate);
if(!ifs)
throw std::runtime_error(filepath + ": " + std::strerror(errno));
auto end = ifs.tellg();
ifs.seekg(0, std::ios::beg);
auto size = std::size_t(end - ifs.tellg());
if(size == 0) // avoid undefined behavior
return {};
std::vector<std::byte> buffer(size);
if(!ifs.read((char*)buffer.data(), buffer.size()))
throw std::runtime_error(filepath + ": " + std::strerror(errno));
return buffer;
}
Run Code Online (Sandbox Code Playgroud)
这是我所知道的最快的方法.它还避免了确定文件中数据大小的常见错误,因为ifs.tellg()在结束时打开文件后不一定与文件大小相同,ifs.seekg(0)理论上不是找到文件开头的正确方法(即使它在大多数地方都有效).
std::strerror(errno)保证错误消息可以在POSIX系统上运行(应该包括Microsoft但不确定).
显然你可以用std::filesystem::path const& filepath它代替std::string你想要的.
此外,特别是对于pre C++17,您可以使用std::vector<unsigned char>或者std::vector<char>如果您没有或想要使用std::byte.
| 归档时间: |
|
| 查看次数: |
1677 次 |
| 最近记录: |