在c中每次读取一个文件多个字节

Read a file a number of bytes per time in c

我正在尝试编写一个关于如何使用 read 每次读取 10 个字节的文件的程序,但是,我不知道该怎么做。我应该如何修改此代码以每次读取 10 个字节。谢谢!!!

#include <unistd.h>  
#include <sys/types.h>
#include <sys/stat.h> 
#include <fcntl.h>
#include <sys/time.h>


int main (int argc, char *argv[])
{
    printf("I am here1\n");
    int fd, readd = 0;
    char* buf[1024];  

    printf("I am here2\n");

    fd =open("text.txt", O_RDWR);
    if (fd == -1)
    {
            perror("open failed");
            exit(1);
    }
    else
    {   
            printf("I am here3\n");

            if(("text.txt",buf, 1024)<0)
                    printf("read error\n");
        else
        {
            printf("I am here3\n");

            /*******************************
            *  I suspect this should be the place I make the modification
            *******************************/
            if(read("text.txt",buf, 1024)<0)
                    printf("read error\n");
            else
            {
                    printf("I am here4\n");
                    printf("\nN: %c",buf);
                    if(write(fd,buf,readd) != readd)
                            printf("write error\n");

            }
        }

    return 0;
}

read() 的最后一个参数是您希望读取的数据的最大大小,因此,要尝试一次读取十个字节,您需要:

read (fd, buf, 10)

您会注意到我还将 first 参数更改为文件描述符而不是文件名字符串。

现在,您可能希望在循环中进行此操作,因为您需要对数据执行某些操作,并且您还需要检查 return 值,因为它可以为您提供 比你要求的少

这样做的一个很好的例子是:

int copyTenAtATime (char *infile, char *outfile) {
    // Buffer details (size and data).

    int sz;
    char buff[10];

    // Try open input and output.

    int ifd = open (infile, O_RDWR);
    int ofd = open (outfile, O_WRONLY|O_CREAT);

    // Do nothing unless both opened okay.

    if ((ifd >= 0) && (ofd >= 0)) {
        // Read chunk, stopping on error or end of file.

        while ((sz = read (ifd, buff, sizeof (buff))) > 0) {
            // Write chunk, flagging error if not all written.

            if (write (ofd, buff, sz) != sz) {
                sz = -1;
                break;
            }
        }
    }

    // Finished or errored here, close files that were opened.

    if (ifd >= 0) close (ifd);
    if (ofd >= 0) close (ofd);

    // Return zero if all okay, otherwise error indicator.

    return (sz == 0) ? 0 : -1;
}

更改 read

中的值
read(fd,buf,10);

来自 man,共 read

ssize_t read(int fd, void *buf, size_t count);

read() attempts to read up to count bytes from file descriptor fd into the buffer starting at buf.

 if(read("text.txt",buf, 1024)<0)// this will give you the error.

第一个参数必须是文件描述符。