因此,我正在使用while循环读取文件。我的班级要建立一个汇编程序。因此,我们基本上必须忽略空白行或注释行(采用这种格式;注释)。除了一件事之外,我一切都正常工作,如果文件由于某种原因以空白行开头,则程序将停止工作。为了尝试解决该问题,我在解释该程序之前先打印出该程序读取的每一行。对于任何其他空行,它只放置一个空行,但是对于第一行,它打印一个0 @。最初,我以为这可能只是程序运行时内存中发生的事情,但每次都为0 @,我认为这绝非偶然。无论如何,对可能出问题的任何帮助都会有所帮助。谢谢!
int findOrigin(FILE *infile)
{
char line[LINE_SIZE];
char origin[LINE_SIZE];
int nonComments = 0;
int hexOrigin = 0;
int lineCount = 0;
int done = 0;
char c;
while (fscanf(infile, "%[^\n]s", line) != EOF && lineCount < LIMIT && !done)
{
lineCount++;
fscanf(infile, "%c", &c); //Get rid of extra newline.
removeSpaces(line);
toUpperCase(line);
if (line[0] != 0 && line[0] != ';')
{
done = 1;
if (!strncmp(line, ".ORIG", 5))
{
nonComments++;
}
if (nonComments > 1)
{
printf("ERROR 1: Missing origin directive. Origin must be first line in program.");
}
else
{
if (line[5] == 'X')
{
sscanf(&line[6], "%s", origin);
hexOrigin = 1;
}
else
{
sscanf(&line[5], "%s", origin);
hexOrigin = 0;
}
}
}
line[0] = 0;
}
int intOrigin = -1;
if (origin > 0 && hexOrigin == 1)
{
if (strlen(origin) > 4)
{
printf("ERROR 2: Bad origin address. Address too big for 16 bits.\n");
}
else
{
intOrigin = fromHexToDecimal(origin);
}
}
else
{
sscanf(origin, "%d", &intOrigin);
}
return intOrigin;
}
void removeSpaces(char line[])
{
char* currentLetter = line;
for (int i = 0; line[i]; i++)
{
if (line[i] != ' ' && line[i] != '\t')
{
*currentLetter = line[i];
currentLetter++;
}
}
*currentLetter = 0;
}
void toUpperCase(char line[])
{
for (int i = 0; line[i]; i++)
{
if (line[i] >= 97 && line[i] <= 122)
{
line[i] -= 32;
}
}
}
所以我有一个正在运行的测试文件,看起来像这样
;Test file for assembly
;This is a comment
.orig x3000
ADD R1, R2, R3
add R0, R3, #10
and R1, R1, R2
AND R0, R3, #-10
L0
BR L1
BRN L0
BRZ L1
BRP L0
BRNZ L1
BRNP L0
BRZP L1
BRNZP L0
LD R1, L2
LDR R1, R2, #-5
L1
NOT R3, R4
ST R5, L2
STR R6, R1, #-5
TRAP x20
TRAP x21
TRAP x22
TRAP x23
TRAP x24
TRAP x25
L2 .FILL 0
L3 .FILL 0
L4 .FILL 0
.END
If I print out each line it looks like this
0@
;Test file for assembly
;This is a comment
.ORIGX3000
ADDR1,R2,R3
ADDR0,R3,#10
ANDR1,R1,R2
ANDR0,R3,#-10
L0
BRL1
BRNL0
BRZL1
BRPL0
BRNZL1
BRNPL0
BRZPL1
BRNZPL0
LDR1,L2
LDRR1,R2,#-5
L1
NOTR3, R4
STR5,L2
STRR6,R1,#-5
TRAPx20
TRAPx21
TRAPx22
TRAPx23
TRAPx24
TRAPx25
L2.FILL0
L3.FILL0
L4.FILL0
.END