如何在 C 中使用读写过去的 BUFSIZ

How to use read and write past BUFSIZ in C

对于一个作业,我应该创建两种方法:方法一将 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() 将 return 读取的字节数或 0(如果它位于文件末尾)。我遇到的问题是了解如何将 read()BUFSIZ 进行比较,然后循环并从它停止的地方开始 read(),直到我到达文件的真正结尾。

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

char buf[BUFSIZ];
ssize_t n;
while((n = read(fd_in, buf, BUFSIZ)) > 0)
    write(fd_out, buf, n);
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

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