文件RecvFile函数中预期的令牌错误

Expected token error in file RecvFile function

本文关键字:令牌 错误 RecvFile 函数 文件      更新时间:2023-10-16

我正在学习一些关于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); 
} 

您有一个do而没有相应的while:

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

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

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

您有一个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应该去的地方添加它(如上面的注释所示)。

您在没有实际提供while();的情况下启动了do

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);