小编Ter*_*ian的帖子

什么是习惯性的C++ 17标准读取二进制文件的方法?

通常我会使用C样式文件IO,但我正在尝试一种现代C++方法,包括使用C++ 17特定的功能std::bytestd::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)

这看起来对吗?这可以改善吗?

c++ io file c++17

1
推荐指数
1
解决办法
1677
查看次数

标签 统计

c++ ×1

c++17 ×1

file ×1

io ×1