Skip to content

fix: Chapter-4/p6.c Hole spanning across buffers#15

Open
Invinc-Z wants to merge 2 commits intoMeiK2333:masterfrom
Invinc-Z:Invinc-Z-patch-1
Open

fix: Chapter-4/p6.c Hole spanning across buffers#15
Invinc-Z wants to merge 2 commits intoMeiK2333:masterfrom
Invinc-Z:Invinc-Z-patch-1

Conversation

@Invinc-Z
Copy link
Contributor

The issue lies in the current solution:

Each time a buffer is read, both f and l are reset to 0, this means each buffer is processed independently, making it impossible to correctly handle holes that span buffer boundaries.
In practice, when the code encounters zero bytes, it does not skip writing them, but continues processing as normal.

test:

  1. compile the make_sparse_file.c by gcc make_sparse_file.c to get sparse file sparse_file

  2. copy file with ./a.out sparse_file dest

  3. ll sparse_flie dest and du sparse_file dest

    $ ll sparse_file dest
    -rw-rw-r-- 1 zhuang zhuang 10485760  1月 30 16:29 dest
    -rw-r--r-- 1 zhuang zhuang 10485760  1月 30 16:29 sparse_file
    $ du sparse_file dest
    44       sparse_file
    10240    dest

this implies that this solution copy a file containing holes, with writing the bytes of 0 to the output file, however, this is not the effect we want to get.

Some improvements are as follows:

  • Fix the cross-buffer boundary issue: Use persistent state variables (in_hole, data_start, hole_start) to track the position in the file and ensure correct handling of holes that span multiple buffers.

  • Optimize the write logic: Use lseek for positioning only when switching from a hole to data, and write data blocks when switching from data to a hole, avoiding unnecessary write operations.

  • Ensure the correct file size: Use ftruncate to make the target file the same size as the source file.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant