简体   繁体   English

C ++ Modulo对齐我的数据

[英]C++ Modulo to align my data

I am compiling several smaller files into one big file. 我正在将几个较小的文件编译为一个大文件。

I am trying to make it so that each small file begins at a certain granularity, in my case 4096. 我正在尝试使每个小文件都以一定的粒度开始,例如4096。

Therefore I am filling the gap between each file. 因此,我填补了每个文件之间的空白。

To do that I used 为此我用了

//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();
}

However iCheck returns 但是iCheck返回

 iCheck = 3503

I expected it to be 0. 我希望它是0。

Does anybody see my mistake? 有人看到我的错误吗?

iStart % 4096 is the number of bytes since the previous 4k-boundary. iStart % 4096上一个4k边界以来的字节数。 You want the number of bytes until the next 4k-boundary, which is (4096 - iStart % 4096) % 4096 . 您需要直到下一个4k边界的字节数,即(4096 - iStart % 4096) % 4096

You could replace the outer modulo operator with an if , since it's only purpose is to correct 4096 to 0 and leave all the other values untouched. 您可以用if代替外部模运算符,因为它的唯一目的是将4096校正为0并保持所有其他值不变。 That would be worthwhile if the value of 4096 were, say, a prime. 如果4096的值是素数,那将是值得的。 But since 4096 is actually 4096, which is a power of 2, the compiler will do the modulo operation with a bit mask (at least, provided that iStart is unsigned), so the above expression will probably be more efficient. 但是由于4096实际上是4096,即2的幂,因此编译器将使用位掩码进行模运算(至少,如果iStart是未签名的),因此上述表达式可能会更有效。

By the way, you're allowed to fseek a file to a position beyond the end, and the file will be filled with NUL bytes. 顺便说一句,您可以将文件查找到末尾以外的位置,并且该文件将填充NUL个字节。 So you actually don't have do all that work yourself: 因此,您实际上并没有自己做的所有事情:

The fseek() function shall allow the file-position indicator to be set beyond the end of existing data in the file. fseek()函数应允许将文件位置指示符设置为超出文件中现有数据的末尾。 If data is later written at this point, subsequent reads of data in the gap shall return bytes with the value 0 until data is actually written into the gap. 如果此时稍后再写入数据,则随后在间隙中读取数据将返回值为0的字节,直到将数据实际写入间隙中为止。 (Posix 2008) (Posix 2008)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM