将文件分割成相等的字节段,用完整字分隔(C/ c++)

Split file into equal byte sections, separated by complete word (C/C++)

本文关键字:分隔 c++ 分割 文件 字节      更新时间:2023-10-16

我需要这样做。以文本文件为例(如下所示)

test.txt
The quick brown fox jumped over the lazy dog

我需要将该文件分割成任意的字节分割。所以上面的文件是45字节(包括EOL/EOF字符)。我基本上想以任意的方式按字节分割。

所以如果我把它分成4部分,我会得到这样的内容:

目前

第1部分:快速b(11字节)

第二部分:小狐狸(11字节)

Part3: mped over t (11 bytes)

Part4: the lazy dog (12 bytes)

(大致如此)

但是我想把它分成完整的单词,所以它看起来像这样

Part1: The quick brown (15 bytes)

Part2: fox jump (9 bytes)

Part3: Over the (8 bytes)

Part4: lazy dog (9 bytes)

或者类似的东西,这样除法就有完整的词。如果有3个单词和6个部分要分割,那么前3个部分应该每个都有一个单词,其余部分应该是空的。这样的:

file: The quick brown

(分成6部分)

Part1:

第二部分:快

Part3:布朗

Part4-6: "

这是我得到的"current"

// Get file size in bytes
off_t fileSize = statBuf.st_size;
// Split a section of file to read for each thread
off_t startSection[NUM_SECTIONS];
off_t endSection[NUM_SECTIONS];
for (int i = 0; i < NUM_SECTIONS; i++) {
    if (i == 0) {
        // Start at 0, end at our interval chunk
        startSection[i] = 0;
        endSection[i] = fileSize / NUM_SECTIONS;
    } else {
        // Start at the last section's end
        startSection[i] = endSection[i-1];
        // End after the next chunk
        endSection[i] = (fileSize / NUM_SECTIONS) * (i + 1);
    }
    // At the last section, add any remaining bytes
    if (i == NUM_SECTIONS - 1) {
        endSection[i] += fileSize % NUM_SECTIONS;
    }
}

我认为我必须窥探文件内容并识别空白/标点符号(我想将标点符号和空白字符视为相同)。但我无法让它以相等的部分执行(任意,可以是3部分,4,5,6等)

任何帮助都是感激的。

如果您事先知道文件的大小,我认为这种方法将是一个很好的起点(仅限C-ish伪代码):

filesize = ???;
nchunks = ???;
fileno = 1;
bytes_processed = 0;
while (bytes_processed < filesize)
{ copy_one_byte();
  if (++bytes_processed >= (filesize / nchunks * fileno))
  { // keep processing to end of word or the end of file, whichever is first
    // then switch to next file
    ++fileno;
  }
}