首页 > 解决方案 > 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;

}

标签: c++socketstcpifstreameof

解决方案


如果文件大小不是SIZE.

此外,即使文件大小是您的精确倍数,SIZE您也会读取最后一个字符,然后eof()不会返回. 直到您尝试阅读下一个字符才会返回,这将触发您的错误消息,.trueeof()trueERROR: 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

推荐阅读