【发布时间】:2020-09-25 09:46:40
【问题描述】:
我有一个类似于下面代码的压缩函数。它基本上从我的应用程序中获取日志文件并使用Zlib 压缩它们。一位用户报告了这样的错误:Failed compressing file: 'C:/ProgramData/AppName/logs/cef.log'; error number 2. 我真的很讨厌 C 和它的错误代码。有人可以指出问题的原因吗?
string contents;
if ( ! fileContents(source, contents))
throw FailedCompressionError{"Failed to get the file contents of '" + source + "'."};
gzFile targetFile{gzopen(target.c_str(), "wb")};
const auto result{gzclose(targetFile)};
if (result != Z_OK)
Logger::Error(
"Failed closing file: '{}'; error number {}; result {}.",
target,
errno,
result
);
if (targetFile == Z_NULL)
throw FailedCompressionError{
"Failed compressing file: '" + source + "'; error number " + to_string(errno) + '.'
};
const auto contentsLength{static_cast<unsigned>(strlen(contents.c_str()))};
auto result{gzwrite(targetFile, contents.c_str(), contentsLength)};
(...)
【问题讨论】:
-
我非常怀疑您的代码是否“基本上”与此摘录在打开后立即关闭流相同。 errno 可以 - anf 应该 - 使用 strerror 可读。只要记住之前将其归零,这样您就可以确保它不会保留以前调用的值