我在sprintf方面遇到问题。它似乎正在修改我的代码的其他部分。我正在从扩展名为.j的文件中读取令牌。但在此之前,我通过从文件中删除.j扩展名,使用pathname.j文件名在文件中创建标签:
j_file是路径名。j:
//Initialize length of j_file pathname
j_file_len = strlen(j_file);
//Initialize
char if_label[j_file_len];
char else_label[j_file_len];
char endif_label[j_file_len];
在这里,我从原始路径名中删除.j扩展名,并将其添加到三个单独的变量中,以便新文件扩展名仅是路径名
for (i = 0; i < j_file_len - 2; i++)
{
if_label[i] = j_file[i];
else_label[i] = j_file[i];
endif_label[i] = j_file[i];
}
//Place null terminator
if_label[j_file_len - 2] = '\0';
else_label[j_file_len - 2] = '\0';
endif_label[j_file_len - 2] = '\0';
//Length of concatenated string
len_concat = strlen(if_label);
在这里,我在文件中搜索“ if”标记,然后将字符串连接到if_label
的末尾,并fprint到文件。
//If token is if
else if (strcmp(tail->token, "if") == 0)
{
printf("There are %d IFS\n",if_count );
printf("IF FOUND\n");
sprintf(if_count_string, "_IF_%d", if_count);
strcat(if_label, if_count_string);
printf("If CONCAT is %s \n",if_label );
//Else will match to IF
else_count = if_count;
//Create ELSE label for branching
sprintf(else_count_string, "_ELSE_%d", else_count);
strcat(else_label, else_count_string);
printf("Else CONCAT is %s \n",else_label );
////
///**** EDIT
//Open file
FILE *ASM = fopen(asm_file, "a");
//Perform operation
fprintf(ASM, "\t; === %s ===\n", tail->token);
//Create IF label
fprintf(ASM, "%s\n",if_label);
//Copy element at top of stack to register
fprintf(ASM, "\tLDR R0, R6, #0\n");
//Clear element from stack
fprintf(ASM, "\tCONST R2, #0\n");
fprintf(ASM, "\tHICONST R2, #0\n");
fprintf(ASM, "\tSTR R2, R6, #0\n");
//Increment stack pointer to point to next element on stack
fprintf(ASM, "\tADD R6, R6, #1\n");
//Compare elements element to 0 (element - 0)
fprintf(ASM, "\tCMPI R0 #0\n");
//If operation false (= 0) Branch to corresponding else label
fprintf(ASM, "\tBRz %s\n", else_label);
//****/
//Close file
fclose(ASM);
//Remove IF label identifier
for (i = len_concat; if_label[i] != '\0'; i++)
{
if_label[i] = '\0';
}
len = strlen(if_label);
printf("new length of if label is %d\n", len);
printf("Trimmed IF IS %s\n",if_label );
//Remove ELSE label identifier
for (i = len_concat; else_label[i] != '\0'; i++)
{
else_label[i] = '\0';
}
len = strlen(else_label);
printf("new length of else label is %d\n", len);
printf("Trimmed ELSE IS %s\n",else_label );
//Increment if counter
if_count++;
}
我期望的输出是,在每次for循环迭代到代码结尾时,修整后的IF和修整后的ELSe应该只打印pathname
:
If CONCAT is pathname_IF_0
Else CONCAT is pathname_ELSE_0
new length of if label is 8
Trimmed IF IS pathname
new length of else label is 8
Trimmed ELSE IS pathname
但是我的IF语句被我不知道的某个代理神秘地修改了。观察代表性输出:
If CONCAT is pathname_IF_0 //CORRECT
Else CONCAT is pathname_ELSE_0 //CORRECT
new length of if label is 1//NOT CORRECT
Trimmed IF IS 0 //WHY?!?!?!?
new length of else label is 8 //CORRECT
Trimmed ELSE IS pathname
由于此if块发生在循环中,因此它弄乱了我的代码的后续迭代。为什么会这样呢?我为此打了个头,无济于事。任何帮助表示赞赏。
编辑:计数变量和字符串变量在if bock之外初始化
int if_count = 0;
int else_count = 0;
char if_count_string[100];
char else_count_string[100];