【发布时间】:2019-10-07 03:07:46
【问题描述】:
当我使用fgets 时,我想忽略/跳过文本文件中的 cmets。
问题是如果一行中的第一个字符开始是#,我只能跳过注释。在我的文本文件中,评论以 # 开头。但是我的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);
....
}
【问题讨论】:
-
我不清楚您是想跳过
A B #Path between A and B.行还是将该行更改为A B? -
我只想阅读 A B 并在 # 出现时跳过该行
-
关于;
fscanf(file, "%40[0-9a-zA-Z]s", ch);字母 's' 是 '%[..]' 中允许的输入字符的一部分,因此会被对fscanf()的调用消耗,因此对fscanf()的发布调用无效