嗨,我正在为我的系统软件(汇编程序、加载程序等)课程做C文件I/O测试程序,我的问题是最后一行读了两次,我记得我的老师告诉我这是由于我错过了一些轻微的语法或错误,我忘了它是什么,请看一看并快速帮助我。
程序
#include<stdio.h>
#include<stdlib.h>
//read from source.txt and write to output.txt
int main()
{
FILE *f1=fopen("source.txt","r");
FILE *f2=fopen("output.txt","w");
int address;
char label[20],opcode[20];
while(!feof(f1))//feof returns 1 if end of file
{
fscanf(f1,"%st%st%d",label,opcode,&address);
printf("%st%st%dn",label,opcode,address);
fprintf(f2,"%st%st%dn",label,opcode,address);
}
int check=fclose(f1);
int check2=fclose(f2);
printf("close status %d %d",check,check2);
return 0;
}
source.txt
NULL LDA 4000
ALPHA STA 5000
BETA ADD 4020// I stopped right here, DID NOT PRESS 'ENTER' , so that ain’t the issue
输出.txt
NULL LDA 4000
ALPHA STA 5000
BETA ADD 4020
BETA ADD 4020
//最后一行两次
终端输出
NULL LDA 4000
ALPHA STA 5000
BETA ADD 4020
BETA ADD 4020
//最后一行两次
我不想最后一行被打印或写两次,我做错了什么,救命!
您可以使用fscanf
的返回值,该值应等于成功扫描的项目数:
while(fscanf(f1,"%st%st%d",label,opcode,&address) == 3) {
printf("%st%st%dn",label,opcode,address);
fprintf(f2,"%st%st%dn",label,opcode,address);
}