0

我正在学习一些关于 C++ 套接字的例子。这里的代码之一有一个错误:在最后一行上方的行中出现“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); 
} 
4

3 回答 3

3

你有一个do没有对应的while

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

fclose(file); 

看起来它应该只是while (true),你不妨坚持在顶部,而不是做do while. 如果返回 0 或更少,则执行将中断循环recv,这分别表示有序关闭和错误。所以改成:

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

fclose(file); 
于 2013-04-05T21:26:18.730 回答
2

您有一个do没有相应的声明while

do // <== THERE IS NO CORRESPONDING while FOR THIS do
{
    rval = recv(sock, buf, sizeof(buf), 0);
    if (rval < 0)
    {
        // ...
    }

    // ...

    do
    {
        // ...
    }
    while (off < rval); // <== This is OK: the "do" has a matching "while"
}
// Nothing here! Should have a "while (condition)"

如果您只想无限期地重复您的循环,那么您应该使用while (true)- 替换do关键字(最好),或者将其添加到缺少的while地方(如上述评论所示)。

于 2013-04-05T21:26:29.450 回答
1

你开始了 ado而没有实际提供 awhile();

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);
} //while() Needs to go here

fclose(file); 
于 2013-04-05T21:26:34.900 回答