Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/sockets/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ ifstream EOF早期执行_C++_Sockets_Tcp_Ifstream_Eof - Fatal编程技术网

C++ ifstream EOF早期执行

C++ ifstream EOF早期执行,c++,sockets,tcp,ifstream,eof,C++,Sockets,Tcp,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 suc

我正在使用套接字编程,目前正试图通过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;
intmain(){
int SIZE=16000;
字符文件缓冲区[大小];
int i=0;
ifstream my_文件(“1MB”,ios::in | ios::binary);
如果(!我的文件){
cout>ch;
if(my_file.eof())
{

cout如果文件大小不是
size
的精确倍数,则看起来您丢弃了文件末尾的数据

此外,即使文件大小是
size
的精确倍数,您也将读取最后一个字符,然后
eof()
将不会返回
true
。除非您尝试读取下一个字符,否则不会返回
eof()
返回
true
,这将触发错误消息,
错误:检测到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

如果文件大小不是
size
的精确倍数,那么如何处理
file\u缓冲区中的内容呢?看起来你只是删除了它。小题大做:
char
不是
unsigned char
。因为你处理的是二进制数据,所以使用
uint8\u t
会更好、更明确。另外,
(!my_file.eof())
不正确。请使用
无符号字符ch;而(my_file>>ch)