[英]When does fgets stop reading a line?
I am debugging my program using gdb, fgets(line, sizeof(line), fp2) reads nothing from a text file. 我正在使用gdb调试程序,fgets(line,sizeof(line),fp2)不会从文本文件读取任何内容。 so the program loops infinity ins side
while(!feof(fp2))
and the EOF is never met i dont know why? 所以程序会
while(!feof(fp2))
循环无限ins边while(!feof(fp2))
并且EOF从未遇到过,我不知道为什么?
I'm putting part of the code for context, 我将部分代码用于上下文,
here is the inputfile: 这是输入文件:
COPY START 1000
FIRST STL RETADR
CLOOP JSUB RDREC
LDA LENGTH
COMP ZERO
JEQ ENDFIL
ZERO WORD 0
RETADR RESW 1
LENGTH RESW 1
BUFFER RESB 4096
RSUB
END FIRST
here is the main program: 这是主程序:
int main(int argc, char *argv[])
{
FILE *fp, *fp2, *fphex;
char line[1000] = "" ;
if (argc != 2)
{
printf("Usage: %s filename\n", argv[0]);
exit(EXIT_FAILURE);
}
if ((fp = fopen(argv[1], "r")) == NULL)
{
printf("Can't open %s\n", argv[1]);
exit(EXIT_FAILURE);
}
fp2 = fopen("intermediate.asm", "w");
fp2 = removecomment(fp,fp2);
rewind(fp2);
while (!feof(fp2))
{
fgets(line, sizeof(line), fp2); /*this fgets reads only 4 bytes of empty spaces*/
parse(line);
}
struct node *print = head;
fphex = fopen("Hex_code", "w");
while(print == NULL)
{
fprintf(fphex, "%s", print->instruction);
print = print->next;
}
return(0);
}
EDIT: 编辑:
While(!feof(File*pointer) was not the problem. while(!feof(File * pointer)不是问题。
i was trying to read from a write only fopen file. 我试图从只写fopen文件中读取。
i resolved it by fclose(file) fopen("file","r")
or as suggested by others w+ mode. 我通过
fclose(file) fopen("file","r")
或其他w +模式建议解决了它。 I think closing and opening in read mode is safer. 我认为以读取模式关闭和打开比较安全。
Ok, here is the problem, you have "w"
as a file opening mode. 好的,这是问题所在,您将
"w"
作为文件打开模式。
fp2 = fopen("intermediate.asm", "w");
it should be 它应该是
fp2 = fopen("intermediate.asm", "r");
file opening modes are 文件打开模式是
than you have +
sign which means: 比您的
+
号意味着:
我认为这是很好的解决在这里 ,如果你更换它会解决while(!feof(fp2))
---> while(!feof(fp2) && !ferror(fp2))
fp2是在写模式“ w”下打开的,因此必须先关闭然后在读模式“ r”下打开,这样才能正确地读取行,人们可能已经发现,而不是说出While(!feof(fp2))。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.