- 我遇到这个错误不是经常性的,无法重现它。
- 正在读取的文件是只读文件,无法删除或修改。
- 代码不完全一样,因为它是我正在编写的更大的东西的一部分,但这是造成问题的代码的重要部分。
- 此代码是用于说明目的,而不是复制,因为1点
我试图读取使用cpp文件读取stat和读取错误()
#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的,但是我想,以知道到底为什么发生这种情况?
PS这不是因为磁盘上的块数。我使用st_size而已
请给出一个最简单的例子,最好是自己编译的例子。我们都懂代码,但我们很少有人在英语课上取得好成绩。 – randomusername
“我得到EOF”是什么意思?究竟什么操作正在返回什么值? –
添加了更完整的代码片段。 EOF我的意思是文件结尾 –