【问题标题】:How to use read and write past BUFSIZ in C如何在C中使用读写过去的BUFSIZ
【发布时间】:2015-04-06 11:54:01
【问题描述】:

对于一个作业,我应该创建两个方法:方法一将read()write() 输入文件到一个空的输出文件,一次一个字节(慢慢地)。

另一种方法将改为使用char buf[BUFSIZ];,其中BUFSIZ 来自<stdio.h>。我们应该将read()write()BUFSIZ 联系起来,这将使事情变得更快。

我们测试每个方法的输入文件只是一个 linux 字典 (/dict/linux.words)。

我已经正确实现了方法一,我一次调用一个字符read()write(),将输入文件复制到输出文件。虽然速度很慢,但至少会复制所有内容。

我的代码如下所示:

// assume we have a valid, opened fd_in and fd_out file.
char buf;
while(read(fd_in, buf, 1) != 0)
    write(fd_out, buf, 1);

但是,对于方法二,我使用BUFSIZ,我无法将每个条目都传输到输出文件中。它在 z 条目中失败,并且不再写入。

所以,我的第一次尝试:

// assume we have a valid, opened fd_in and fd_out file
char buf[BUFSIZ];
while(read(fd_in, buf, BUFSIZ) != 0)
    write(fd_out, buf, BUFSIZ);

没用。

我知道read() 将返回读取的字节数,如果它位于文件末尾,则返回 0。我遇到的问题是了解如何将read()BUFSIZ 进行比较,然后循环并从停止的位置开始read(),直到我到达文件的真正末尾。

【问题讨论】:

  • ...result = read(..); if (result < BUFSIZ) .. 似乎有些明显。
  • @Jongware 现在可以了:/ 因为期中考试/项目,我已经睡了两天了,所以我的大脑很煎熬 :(

标签: c linux file system stdio


【解决方案1】:

由于您的文件很可能不是BUFSIZ 的精确倍数,您需要检查实际读取的字节数,以便正确写入最后一个块,例如

char buf[BUFSIZ];
ssize_t n;
while((n = read(fd_in, buf, BUFSIZ)) > 0)
    write(fd_out, buf, n);

【讨论】:

  • 感谢您的帮助!这很有意义。
  • 请注意,您的文件在大多数情况下可能大于 BUFSIZ,因此您必须进行多次读取
  • @Pandrei:是的,这就是为什么 read 和 write 调用嵌入到 while 循环中。
【解决方案2】:
this code:

// assume we have a valid, opened fd_in and fd_out file
char buf[BUFSIZ];
while(read(fd_in, buf, BUFSIZ) != 0)
    write(fd_out, buf, BUFSIZ);

leaves much to be desired, 
does not handle a short remaining char count at the end of the file, 
does not handle errors, etc.

a much better code block would be:

// assume we have a valid, opened fd_in and fd_out file
char buf[BUFSIZ];
int readCount;  // number of bytes read
int writeCount; // number of bytes written

while(1)
{
    if( 0 > (readCount = read(fd_in, buf, BUFSIZ) ) )
    { // then, read failed
         perror( "read failed" );
         exit( EXIT_FAILURE );
    }

    // implied else, read successful

    if( 0 == readCount )
    {  // then assume end of file
        break; // exit while loop
    }

    // implied else, readCount > 0

    if( readCount != (writeCount = write( fd_out, buf, readCount ) ) )
    { // then, error occurred
        perror( "write failed" );
        exit( EXIT_FAILURE );
    }

    // implied else, write successful
} // end while

注意:我没有包括关闭输入/输出文件语句 但是,在每次调用 exit() 之前,确实需要添加

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-02
    • 2015-09-08
    • 2023-03-06
    • 2013-01-29
    相关资源
    最近更新 更多