首页 > 解决方案 > File.exe 已因 Fseek 触发断点

问题描述

我正在尝试确定我正在读取的文件有多大(以字节为单位),因此我使用 Fseek 跳转到末尾并触发了错误:file.exe 已触发断点。Heses 代码: FileUtils.cpp: #include "FileUtils.h"

namespace impact {

    std::string read_file(const char* filepath)
    {
        FILE* file = fopen(filepath, "rt");
        fseek(file, 0, SEEK_END);
        unsigned long length = ftell(file);
        char* data = new char[length + 1];
        memset(data, 0, length + 1);
        fseek(file, 0 ,SEEK_SET);
        fread(data, 1, length, file);
        fclose(file);

        std::string result(data);
        delete[] data;
        return result;
    }

}

文件实用程序.h:

    #pragma once
#include <stdio.h>
#include <string>
#include <fstream>


namespace impact {
    std::string read_file(const char* filepath);
}

如果需要更多信息,请向我询问,我非常乐意提供更多信息!

标签: c++visual-studiofstream

解决方案


您以 C 方式执行此操作,C++ 具有更好的(在我看来)处理文件的方式。

您的错误看起来可能是由于文件未正确打开而引起的(您需要检查 if file != nullptr)。

要在 C++17 中执行此操作,您应该使用标准库filesystem (注意:您也可以experimental/filesystem使用std::experimental::filesystem命名空间在 C++11 中执行此操作)

例子:

std::string read_file(const std::filesystem::path& filepath) {
    auto f_size = std::filesystem::file_size(filepath);
    ...
}

此外,要在 C++ 中读取文件,您不需要知道文件的大小。您可以使用流:

std::string read_file(const std::filesystem::path& filepath) {
   std::ifstream file(filepath); // Open the file

   // Throw if failed to open the file
   if (!file) throw std::runtime_error("File failed to open");

   std::stringstream data; // Create the buffer
   data << file.rdbuf(); // Read into the buffer the internal buffer of the file
   return data.str(); // Convert the stringstream to string and return it
}

如您所见,C++ 的执行方式要短得多,调试起来也容易得多(当出现问题时,会抛出带有描述的有用异常)


推荐阅读