当我使用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);
....
}
发布于 2019-05-21 03:19:05
方法名也是不同的,但是我使用这个版本对吗?忽略我的脏方法line_is_comment -从第一个版本开始,除非你想玩;-)
扩展测试输入:
#Paths
A B #Path between A and B.
D C #Path between C and D.
E F
G H
输出:
rest of line read
AB rest of line read
DC rest of line read
EF rest of line read
GH rest of line read
#include <stdio.h>
bool line_is_comment(const char *s)
{
char *commentPos = const_cast<char*>(strchr(s, '#'));
if(commentPos != NULL) {
*commentPos = 0; // cut-off chars after comment
//return true; // or false then to accept the line
return commentPos == s;
}
return false;
}
#define BUFSIZE 50
int main()
{
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);
}
int x;
while(!feof(file)) {
x = fscanf(file, "%40[0-9a-zA-Z]s", ch);
if(x == 0) {
ch[0] = fgetc(file);
if(ch[0] == '#' || ch[0] == '\n') {
if(ch[0] != '\n') fgets(ch, BUFSIZE, file);
printf(" rest of line read\n");
}
} else if(x<0) break;
else {
printf("%c",*ch); // continue with ... undisclosed part here
}
}
return 0;
}
https://stackoverflow.com/questions/56226129
复制相似问题