当我使用fgets
时,我想忽略/跳过文本文件中的注释。
问题是,只有当一行的第一个字符以#开头时,我才能跳过注释。在我的文本文件中,注释以#
开头。但是我的file.txt
中有一些#
不是一行的第一个字符,如下所示;
#Paths
A B #Path between A and B.
D C #Path between C and D.
A是我的第一个节点,B是我的第二个节点,当#出现时,我想忽略文本的其余部分,直到下一行。我的新节点应该是D和C等。我只能在fopen函数中使用"r“。我尝试过fgets
,但它逐行读取,fgetc
也没有帮助。
bool ignore_comments(const char *s)
{
int i = 0;
while (s[i] && isspace(s[i])) i++;
return (i >= 0 && s[i] == '#');
}
FILE *file;
char ch[BUFSIZE];
file = fopen("e.txt", "r");
if (file == NULL) {
printf("Error\n");
fprintf(stderr, "ERROR: No file input\n");
exit(EXIT_FAILURE);
}
while(fgets(ch, BUFSIZE, file) != NULL)
{
if (line_is_comment(ch)) {
// Ignore comment lines.
continue;
printf("%c",*ch);
}
fscanf(file, "%40[0-9a-zA-Z]s", ch);
....
}
https://stackoverflow.com/questions/56226129
复制相似问题