Copy a file block per block in C

2019-07-19 02:20发布

问题:

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. How can I do that?

回答1:

Try using fread

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

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



回答2:

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.



回答3:

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.



标签: c file copy block