我试图在c中制作SIC汇编程序,制作了一个小型测试程序来搜索" START"关键字并从汇编代码文件中获取起始地址。然后在第一遍时将它们写在另一个文件中。代码没有用。记住它有什么不对吗?
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main(int argc, char *argv[])
{
FILE *source;
FILE *intermediate;
rewind(source);
char word[10];
unsigned int address = 0;
char start[5] = "START";
source = fopen(argv[1],"r");
intermediate = fopen(argv[2],"r+");
while(strcmp(word,start) != 0)
{
fscanf(source, "%s", word);
}
fscanf(source, "%x", address);
fprintf(intermediate, "%x", address);
fprintf(intermediate, "%s", word);
return(0);
}
这是汇编输入:
COPY START 1000
FIRST STL RETADR
CLOOP JSUB RDREC
LDA LENGTH
COMP ZERO
JEQ ENDFIL
JSUB WRREC
J CLOOP
ENDFIL LDA EOF
STA BUFFER
LDA THREE
STA LENGTH
JSUB WRREC
LDL RETADR
RSUB
EOF BYTE C'EOF'
THREE WORD 3
ZERO WORD 0
RETADR RESW 1
LENGTH RESW 1
BUFFER RESB 4096
答案 0 :(得分:1)
正如我和其他人在评论中指出的,你有几个错误。
1)使用未初始化的变量(word)
2)在文件未打开时倒带
3)字符串的数组太短(开始)
4)fscanf的错误参数(地址而不是&amp;地址)
除此之外还有其他问题,如:
1)fscanf中缓冲区溢出的风险
2)缺少对EOF的处理
3)缺少文件关闭
修复上述内容后,代码可能如下所示:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main(int argc, char *argv[])
{
FILE *source;
FILE *intermediate;
char word[10];
unsigned int address = 0;
const char start[] = "START";
source = fopen(argv[1],"r"); // Missing check of argc and successful file open
intermediate = fopen(argv[2],"w"); // Missing check of argc and successful file open
do
{
if (fscanf(source, "%9s", word) != 1)
{
printf("Illegal source file. START not found\n");
fclose(source);
fclose(intermediate);
exit(1);
}
} while(strcmp(word, start) != 0);
fscanf(source, "%x", &address); // Missing check of return value being 1
fprintf(intermediate, "%x", address);
fprintf(intermediate, "%s", word);
fclose(source);
fclose(intermediate);
return(0);
}
最后请注意,代码仍然会遗漏重要的检查,例如提供的参数数量,成功的文件打开以及扫描地址时fscan
的返回值。