簡體   English   中英

每次在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)

您會注意到,我還將第一個參數更改為文件描述符,而不是文件名字符串。

現在,您可能希望循環執行此操作,因為您希望對數據進行處理,並且還需要檢查返回值,因為返回值可能會比您想要的要

一個很好的例子是:

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

manread

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

read()嘗試從文件描述符fd讀取最多計數的字節到緩沖區(從buf開始)。

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

第一個參數必須是文件描述符。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM