【问题标题】:Recursive copy function to copy data from socket to a file. What's wrong?递归复制函数将数据从套接字复制到文件。怎么了?
【发布时间】:2017-06-25 18:56:15
【问题描述】:

我的递归复制功能适用于文件,但不适用于套接字到文件。我相信这是因为文件是“缓冲的”输入/输出。套接字没有缓冲对吗?那么如何让我的复印机同时处理缓冲/非缓冲输入输出呢?

这是我的复印机功能。

/* file_download() - function to download a file.
 */
size_t file_download(int sockfd, FILE *fout) {
    char data[CHUNK_SIZE];
    int bytesRead, bytesWritten;
    static size_t total_bytes = 0;

    bytesRead = read(sockfd, data, sizeof(data));
    if(bytesRead > 0)
        bytesWritten = fwrite(data, 1, bytesRead, fout); /* Fixed this line */
    if(bytesWritten == bytesRead)
        return total_bytes;
    else
        total_bytes += bytesWritten;
    file_download(sockfd, fout);
}

它所做的只是在没有缓冲时复制一个字节的数据。但是,它在缓冲输入/输出时会复制整个内容。解决此问题的任何帮助将不胜感激。提前致谢。

【问题讨论】:

  • 你为什么要用递归做这样的事情?
  • 递归出了什么问题。
  • fwrite(data, bytesRead, 1, fout) 应该是 fwrite(data, 1, bytesRead, fout)。阅读fwrite 文档。
  • 好的,谢谢,我也会阅读 fwrite 的文档。

标签: c sockets recursion copy


【解决方案1】:

这是实际有效的代码,但这是因为 Antti Haapala 让我知道我在 fwrite 上有两个参数后备词...但这就是有效的。

/* file_download() - function to download a file.
 */
size_t file_download(int sockfd, FILE *fout) {
    char data[CHUNK_SIZE];
    int bytesRead, bytesWritten;
    static size_t total_bytes = 0;

    bytesRead = read(sockfd, data, sizeof(data));
    if(bytesRead > 0)
        bytesWritten = fwrite(data, 1, bytesRead, fout);
    if(bytesRead == 0)
        return total_bytes;
    else if(bytesWritten == bytesRead)
        total_bytes += bytesWritten;
    else
        return -1;
    file_download(sockfd, fout);
}

【讨论】:

  • 您不应该对非递归问题使用递归。此代码不能扩展到大文件。迭代。
猜你喜欢
  • 2019-07-10
  • 2016-07-28
  • 1970-01-01
  • 1970-01-01
  • 2010-10-06
  • 2011-10-27
  • 2011-07-22
  • 2011-02-27
相关资源
最近更新 更多