c++ - 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 方式执行此操作,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++ 的执行方式要短得多,调试起来也容易得多(当出现问题时,会抛出带有描述的有用异常)
推荐阅读
- python - 如何让我的代码用单引号打印?
- python - 单击 Flask 中的提交按钮时加载新页面
- websphere - 无法刷新用于在 Watson Studio 上共享 Jupyter Notebook 的永久链接。有什么修复吗?
- node.js - bcrypt.compare() 总是返回 false
- oracle - 在 oracle 中将表函数与选择查询集成
- sql - 在oracle sql中从最后一个到第一个注释写注释
- android - Android:Redmi note 5 pro (Android 9) 通过 wifi 接入点网络中止 API 连接
- python - 在 python 中使用 bincount numpy 提高 groupby pandas 的性能
- flutter - Flutter 应用程序在 Android 设备中调用 Amplify 的配置方法恢复应用程序时抛出错误
- java - 如何将文本大小绑定到 javafx 中的滑块?