C++ C++;模来对齐我的数据

C++ C++;模来对齐我的数据,c++,math,modulo,granularity,C++,Math,Modulo,Granularity,我正在把几个小文件编译成一个大文件 我正试图使每个小文件以一定的粒度开始,在我的例子4096中 因此,我正在填补每个文件之间的空白 我过去经常这样做 //Have a look at the current file size unsigned long iStart=ftell(outfile); //Calculate how many bytes we have to add to fill the gap to fulfill the granularity unsigned long

我正在把几个小文件编译成一个大文件

我正试图使每个小文件以一定的粒度开始,在我的例子4096中

因此,我正在填补每个文件之间的空白

我过去经常这样做

//Have a look at the current file size
unsigned long iStart=ftell(outfile);

//Calculate how many bytes we have to add to fill the gap to fulfill the granularity
unsigned long iBytesToWrite=iStart % 4096;

//write some empty bytes to fill the gap
vector <unsigned char>nBytes;
nBytes.resize(iBytesToWrite+1);
fwrite(&nBytes[0],iBytesToWrite,1,outfile);

//Now have a look at the file size again
iStart=ftell(outfile);

//And check granularity
unsigned long iCheck=iStart % 4096;
if (iCheck!=0)
{
    DebugBreak();
}
我以为是0


有人看到我的错误了吗?

iStart%4096
是自上一个4k边界以来的字节数。您需要直到下一个4k边界的字节数,即
(4096-iStart%4096)%4096

您可以使用
if
替换外部模运算符,因为它的唯一目的是将
4096
更正为
0
,并保留所有其他值不变。如果4096的值是,比如说,一个素数,那么这将是值得的。但由于4096实际上是4096,这是2的幂,编译器将使用位掩码执行模运算(至少,假设iStart是无符号的),因此上述表达式可能更有效

顺便说一下,您可以将文件fseek到末尾以外的位置,并且该文件将填充NUL字节。所以你实际上不需要自己做所有的工作:

fseek()函数应允许将文件位置指示器设置在文件中现有数据的末尾之外。如果随后在此点写入数据,则间隙中数据的后续读取将返回值为0的字节,直到数据实际写入间隙。

您需要将,
((iStart+4095)/4096)*4096)-iStart
四舍五入。
 iCheck = 3503