开发者

Copy a file block per block in C

I'm trying to divide a file into an x ammount of blocks of size y (in bytes), so that I can copy each block individually.开发者_如何学C How can I do that?


Try using fread

char buffer[ysize];
fread(buffer, ysize, 1, fp);

Each time you read ysize bytes in buffer from the file.


Some struct stat structures have additional members in them that prove useful when copying files:

     st_blksize  The optimal I/O block size for the file.

     st_blocks   The actual number of blocks allocated for the file in
                 (check local system).

If the block size you read is an even multiple of st_blksize you tend to get more efficient reading of the file.

   size_t   desiredSize = 1E4;                // largest buffer size to read into
   size_t   blocks = desiredSize / st.st_blksize;
   if ( blocks < 1 )              // fail safe test
       blocks = 1;
   size_t   true_size = blocks * st.st_blksize;     // this is the size to read
   char *buffer = malloc(true_size);

Failing st_blksize, <stdio.h> provides a BUFSIZ macro for buffer size.


x = fopen ( "x" , "rb");
if (x==NULL) {perror("file could not be opened"); exit(1);}

y = fopen ( "y" , "wb");
if (x==NULL) {perror("file could not be opened"); exit(1);}

char* buf = (char*) malloc (sizeof(char)*1024); //1024 is buffer size

To read 1024 chars into the buffer:

fread(buf, sizeof(char), 1024, x);

You do the rest.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜