gpt4 book ai didi

c++ - 文件 RecvFile 函数中的预期标记错误

转载 作者:太空宇宙 更新时间:2023-11-04 15:46:31 26 4
gpt4 key购买 nike

我正在学习一些有关 C++ 套接字的示例。其中一个代码here出现错误:在最后一行上方的行中出现“expect token while got fclose”

代码对我来说似乎没问题,所以我不知道这里有什么问题。

欢迎任何想法。

void RecvFile(int sock, const char* filename) 
{
int rval;
char buf[0x1000];
FILE *file = fopen(filename, "wb");
if (!file)
{
printf("Can't open file for writing");
return;
}

do
{
rval = recv(sock, buf, sizeof(buf), 0);
if (rval < 0)
{
// if the socket is non-blocking, then check
// the socket error for WSAEWOULDBLOCK/EAGAIN
// (depending on platform) and if true then
// use select() to wait for a small period of
// time to see if the socket becomes readable
// again before failing the transfer...

printf("Can't read from socket");
fclose(file);
return;
}

if (rval == 0)
break;

int off = 0;
do
{
int written = fwrite(&buf[off], 1, rval - off, file);
if (written < 1)
{
printf("Can't write to file");
fclose(file);
return;
}

off += written;
}
while (off < rval);
}

fclose(file);
}

最佳答案

你有一个没有相应whiledo:

do
{
// ...
do
{
// ...
}
while (off < rval);
}
// No while here

fclose(file);

它似乎应该只是 while (true),您不妨将其放在顶部,而不是执行 do while。如果 recv 返回 0 或更少,则执行将从循环中中断,这分别表示有序关闭和错误。所以将其更改为:

while (true)
{
// ...
do
{
// ...
}
while (off < rval);
}

fclose(file);

关于c++ - 文件 RecvFile 函数中的预期标记错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15843847/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com