C 中每个块复制一个文件块

发布于 2024-11-10 09:31:35 字数 62 浏览 1 评论 0原文

我试图将一个文件分成 x 个大小为 y (以字节为单位)的块,以便我可以单独复制每个块。我怎样才能做到这一点?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

愛上了 2024-11-17 09:31:35

尝试使用 fread

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

每次从文件中读取缓冲区中的 ysize 字节时,

Try using fread

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

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

厌倦 2024-11-17 09:31:35

一些 struct stat 结构中包含其他成员,这些成员在复制文件时非常有用:

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

如果您读取的块大小是 st_blksize 的偶数倍,您往往会更有效地读取文件。

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

st_blksize 失败,提供缓冲区大小的 BUFSIZ 宏。

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.

拥醉 2024-11-17 09:31:35
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

要将 1024 个字符读入缓冲区:

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

您将完成其余的工作。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文