Copy a file block per block in C

£可爱£侵袭症+ 提交于 2019-12-24 04:58:10

问题


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.



来源:https://stackoverflow.com/questions/6162421/copy-a-file-block-per-block-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!