通常我会使用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)
这看起来对吗?这可以改善吗?