【发布时间】:2017-01-20 22:42:21
【问题描述】:
我正在尝试构造一个字符串 - 对于循环中的每 80 个字符,在行首添加 7 个制表符,并在末尾添加一个新行。
它应该打印出 7 个标签,然后是 80 个字符,然后是 1 个新行,依此类推。
然而,奇怪的事情正在发生。它在前 2 个字符之后直接打印一个新行,然后从那时起一切都倾斜了。
我也不确定为什么我需要 % 40 而不是 % 80 - 是因为有 2 个字节吗?
我认为我通常被 2 个字节弄糊涂了。
void do_file(FILE *in, FILE *out, OPTIONS *options)
{
char ch;
int loop = 0;
int sz1,sz2,sz3;
int seeker = offsetof(struct myStruct, contents.datas);
//find total length of file
fseek(in, 0L, SEEK_END);
sz1 = ftell(in);
//find length from beggining to struct beginning and minus that from total length
fseek(in, seeker, SEEK_SET);
sz2 = sz1 - ftell(in);
int tabs = (sz2 / 80) * 8;// Total size / size of chunk * 8 - 7 tabs and 1 new line char
sz3 = ((sz2 + 1 + tabs) * 2); //Total size + nuls + tabs * 2 for 2 bytes
char buffer[sz3];
char *p = buffer;
buffer[0] = '\0';
while (loop < sz2)
{
if(loop % 40 == 0){
//Add 7 tabs to the beginning of each new line
p += sprintf(p, "%s", "\t\t\t\t\t\t\t");
}
fread(&ch, 1, 1, in);
//print hex char
p += sprintf(p, "%02X", (ch & 0x00FF));
if(loop % 40 == 0){
//Add a new line every 80 chars
p += sprintf(p, "%s", "\n");
}
strcat(buffer, p);
loop++;
}
printf("%s", buffer);
}
【问题讨论】:
-
strcat手册页上写着The strings may not overlap。另外你确定buffer够大吗? -
它应该打印出 7 个制表符,然后是 80 个字符,然后是 1 个新行等等。 - 你的意思是 16 进制表示 的 80 个字符吗? (即 160 个字符)或 40 个字符的十六进制表示,输出需要 80 个字符?
-
我猜总共 40 个十六进制字符 80 个字符
标签: c string printf concatenation modulo