【发布时间】:2019-11-04 03:04:23
【问题描述】:
我正在处理的代码涉及读取具有以下结构的输入文件:
(spaces)name(spaces) val (whatever) \n
(spaces)name(spaces) val (whatever) \n
(spaces)name(spaces) val (whatever) \n
其中空格表示任意数量的空格。我的代码应该同时给出名称和值。还有另一种情况,在“#”之后的行中的所有内容都被忽略(视为注释)。输出应该是:
"name: (name) value: val \n"
代码大部分都在工作,除了它添加了一个额外的行,它将创建一个 set name= null 和 val 到最后读取的数字是什么。例如我的测试文件:
a 12
b 33
#c 15
nice 6#9
输出是:
Line after: a 12
name: a value: 12 :
Line after: b 33
name: b value: 33 :
Line after: # c 15
Line after: nice 6#9
name: nice value: 6 :
Line after:
name: value: 6 : //why is this happening
代码在这里。
void readLine(char *filename)
{
FILE *pf;
char name[10000];
char value[20];
pf = fopen(filename, "r");
char line[10000];
if (pf){
while (fgets(line, sizeof(line), pf) != NULL) {
//printf("Line: %s\n",line);
printf("Line after: %s\n",line);
while(true){
int i=0;
char c=line[i]; //parse every char of the line
//assert(c==' ');
int locationS=0; //index in the name
int locationV=0; //index in the value
while((c==' ')&& i<sizeof(line)){
//look for next sequence of chars
++i;
c=line[i];
if(c=='#'){
break;
}
}
if(c=='#'){ break;}
assert(c!=' ');
while (c!=' '&&i<sizeof(line))
{
name[locationS]=c;
locationS++;
//printf("%d",locationS);
++i;
c=line[i];if(c=='#'){
break;
}
}
if(c=='#'){ break;}
assert(c==' ');
while(c==' '&&i<sizeof(line)){
//look for next sequence of chars
++i;
c=line[i];
if(c=='#'){
break;
}
}
if(c=='#'){ break;}
assert(c!=' ');
printf("\n");
while ((c!=' '&& c!='\n')&&i<sizeof(line))
{
value[locationV]=c;
locationV++;
++i;
c=line[i];if(c=='#'){
break;
}
}
printf("name: %s value: %s : \n",name, value);
memset(&name[0], 0, sizeof(name));
memset(&value[0], 0, sizeof(value));
break; //nothing interesting left
}
}
fclose(pf);
}else{
printf("Error in file\n");
exit(EXIT_FAILURE);
}
}
【问题讨论】:
-
尝试使用 feof() 而不是 fgets()
-
其他都一样吗?
-
i<sizeof(line)应该是i<strlen(line)你还有其他逻辑错误。 (从您的输出来看,您的文件末尾似乎有一个额外的'\n') -
@Dushara - 否。
fgets()的使用是正确的。 -
@DavidC.Rankin 您能否更具体地了解额外的逻辑错误?