c++ - ifstream EOF 提前执行
问题描述
我正在使用套接字编程,目前正在尝试一次通过 16KB 传输 1MB 文件。数据最初一次传输 16KB;但是,我的 ifstream 过早地到达 EOF,这使得文件传输不完整。
int main() {
int SIZE = 16000;
char file_buffer[SIZE];
int i = 0;
ifstream my_file("1MB", ios::in | ios::binary);
if (!my_file) {
cout << "No such file";
} else {
io_service io_service;
// socket creation
ip::tcp::socket client_socket(io_service);
client_socket
.connect(
tcp::endpoint(
address::from_string("127.0.0.1"),
9999));
while(!my_file.eof()) {
char ch;
my_file >> ch;
if(my_file.eof())
{
cout << "File Buffer: " << file_buffer << endl;
cout << "ERROR: EOF DETECTED" << endl;
break;
}
else if (i == SIZE)
{
sendData(client_socket, file_buffer);
memset(file_buffer, 0, sizeof file_buffer);
i = 0;
} else
{
file_buffer[i] = ch;
i++;
}
}
}
my_file.close();
return 0;
}
解决方案
如果文件大小不是SIZE
.
此外,即使文件大小是您的精确倍数,SIZE
您也会读取最后一个字符,然后eof()
不会返回. 直到您尝试阅读下一个字符才会返回,这将触发您的错误消息,.true
eof()
true
ERROR: EOF DETECTED
更多信息在这里:
为什么iostream::eof()
在循环条件内(即while (!stream.eof())
)被认为是错误的?
另一种方法:
unsigned i = 0;
while(my_file >> file_buffer[i]) { // loop for as long as extracting succeeds
if(++i == SIZE) {
sendData(client_socket, file_buffer, i); // add a size parameter
// memset(file_buffer, 0, sizeof file_buffer); // why waste the time?
i = 0;
}
}
if(i) sendData(client_socket, file_buffer, i); // send the last part in the buffer
推荐阅读
- vba - Word:在没有第一行的表格列中设置书签的宏
- git - git checkout 版本,包括子模块
- javascript - 使用 webpack 安装 vue.js 2 时出现 Npm 错误
- python - 如何处理 3d 卷积神经网络的数据?
- vue.js - Nuxt 客户端渲染的 DOM 与服务器渲染的内容不匹配
- javascript - 随机谷歌未定义错误
- speech-recognition - PocketSphinx - 如何理解 getHypstr() 何时返回空而 getInSpeech() 返回 True?
- linux - 如何在 Bash 中构建条件 while 语句?
- javascript - 无法在 Express 中使用 `cookie-parser` 设置 Cookie
- pandas - 如何在 pandas 中使用计数进行 vlookup