【问题标题】:Read a file a number of bytes per time in c在c中每次读取文件多个字节
【发布时间】:2015-04-08 04:22:08
【问题描述】:

我正在尝试编写一个程序,说明如何使用 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;
}

【问题讨论】:

  • if(("text.txt",buf, 1024)&lt;0) 这行会做什么??

标签: c file io byte fread


【解决方案1】:

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

read (fd, buf, 10)

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

现在,您可能希望循环使用它,因为您需要对数据执行某些操作,并且您还需要检查返回值,因为它可以为您提供更少的值你要求的。

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

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

【讨论】:

    【解决方案2】:

    更改read中的值,

    read(fd,buf,10);
    

    来自manread

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

    read() 尝试将文件描述符 fd 中的 count 个字节读入缓冲区,从 buf 开始。

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

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

    【讨论】:

      猜你喜欢
      • 2014-12-12
      • 1970-01-01
      • 1970-01-01
      • 2015-12-11
      • 2020-09-17
      • 2012-01-24
      • 2021-03-07
      • 1970-01-01
      • 2020-11-20
      相关资源
      最近更新 更多