2015-04-08 47 views
0

我想寫一個程序如何讀取一個文件每次使用10個字節讀取,但是,我不知道該怎麼去做。我應該如何修改此代碼以每次讀取10bytes。謝謝!!!!在c中每次讀取一個文件的字節數

#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; 
} 
+0

'if((「text.txt」,buf,1024)<0)'這行會做什麼? –

回答

1

read()最後一個參數是你想讀的話,嘗試和一次讀取10個字節的數據的最大尺寸,你將需要:

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

變化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. 

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