【发布时间】:2015-07-06 18:50:16
【问题描述】:
- 我不经常遇到此错误,无法重现。
- 正在读取的文件是只读文件,不能删除或修改。
- 代码并不完全相同,因为它是我正在编写的更大内容的一部分,但这是导致问题的代码的重要部分。
- 此代码仅用于解释目的,而不是因为第 1 点而重现问题
我正在尝试使用
读取文件#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <memory>
#include <exception>
#include <iostream>
#include <glog/logging.h>
using namespace std;
int main() {
string fileName="blah";
struct stat fileStat;
int status = ::stat(fileName.c_str(), &fileStat);
if (status != 0) {
LOG(ERROR) << "Error stating the file";
}
size_t fileSize = fileStat.st_size;
// fileSize is 79626240. I am trying to read block starting from
// 67108864 bytes, so there will be 1251736
size_t fileBlockSize = 16 * 1024 * 1024;
size_t numBlocks = fileSize / fileBlockSize;
size_t offset = numBlocks;
size_t actualSize = fileSize - offset * fileBlockSize;
if (actualSize == 0) {
LOG(INFO) << "You read the entire file";
return 1;
}
int fd = ::open(fileName.c_str(), O_RDONLY);
if (fd < 0) {
throw std::runtime_error("Error opening the file");
} else if (offset > 0 && lseek(fd, offset, SEEK_SET) < 0) {
throw std::runtime_error("Error seeking the file");
}
uint64_t readBlockSize = 256 * 1024;
char *data = new char[readBlockSize + 1];
uint64_t totalRead = 0;
while (totalRead < actualSize) {
ssize_t numRead = ::read(fd, data, readBlockSize);
// Use the data you read upto numRead
if (numRead == 0) {
LOG(ERROR) << "Reached end of file";
break;
} else if (numRead < 0) {
throw std::runtime_error("read unsuccessful");
}
totalRead += numRead;
}
if (totalRead != actualSize) {
LOG(ERROR) << "Error reading the file";
}
}
如果您想象我将文件切成 16 mybtes 大小的块,然后读取最后一个块。我正在以较小的大小循环读取块,但是在完成读取整个块之前我得到了 EOF。 stat 报告的大小是否会大于文件中数据的大小?
我看到的输出:
Reached end of file
Error reading the file
我不需要其他解决方案,我可以做其他事情,例如 lseek 到 END 但是我想知道为什么会这样?
PS 这不是因为磁盘上的块数。我正在使用 st_size,仅此而已
【问题讨论】:
-
请给出一个最低限度完整的示例,最好是一个可以自行编译的示例。我们都懂代码,但很少有人在英语课上取得好成绩。
-
“我得到 EOF”是什么意思?究竟是什么操作返回了什么值?
-
添加了更完整的 sn-p 代码。 EOF 我的意思是文件结束
-
还添加了头文件。这段代码可能会编译,但这里写的代码更少,更多的是为了演示我正在尝试做的事情