【问题标题】:File.exe has Triggered a Breakpoint because of FseekFile.exe 已因 Fseek 触发断点
【发布时间】:2020-02-27 18:25:48
【问题描述】:

我正在尝试确定我正在读取的文件有多大(以字节为单位),因此我使用 Fseek 跳转到末尾并触发了错误:file.exe 已触发断点。 赫斯代码: 文件实用程序.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;
    }

}

FileUtils.h:

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


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

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

【问题讨论】:

标签: c++ visual-studio fstream


【解决方案1】:

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

您的错误看起来可能是因为文件没有正确打开(您需要检查是否file != nullptr)。

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

例子:

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++ 的执行方式要短得多,调试起来也容易得多(当出现问题时,会抛出带有描述的有用异常)

【讨论】:

  • 它说file_size不是文件系统的成员。有解决办法吗?
  • file_size 是在 C++17 中添加的,因此请确保您使用的是 C++17 编译器和 (不是实验性/文件系统)标头。否则使用 C++11 的实验/文件系统和 std::experimental::filesystem
  • 我尝试使用文件系统而不是实验性/文件系统,但是当我这样做时说文件系统不是命名空间
  • std::filesystem 我猜你错过了标准部分?
  • 我也包括了,我也在使用 Visual Studio 2019
猜你喜欢
  • 2021-12-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-16
  • 1970-01-01
相关资源
最近更新 更多