首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何使用fopen跳过c编程中的注释

如何使用fopen跳过c编程中的注释
EN

Stack Overflow用户
提问于 2019-05-21 02:11:09
回答 1查看 936关注 0票数 0

当我使用fgets时,我想忽略/跳过文本文件中的注释。

问题是,只有当一行的第一个字符以#开头时,我才能跳过注释。在我的文本文件中,注释以#开头。但是我的file.txt中有一些#不是一行的第一个字符,如下所示;

代码语言:javascript
复制
#Paths
A B #Path between A and B.
D C #Path between C and D.

A是我的第一个节点,B是我的第二个节点,当#出现时,我想忽略文本的其余部分,直到下一行。我的新节点应该是D和C等。我只能在fopen函数中使用"r“。我尝试过fgets,但它逐行读取,fgetc也没有帮助。

代码语言:javascript
复制
    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);
....
}
EN

回答 1

Stack Overflow用户

发布于 2019-05-21 03:19:05

方法名也是不同的,但是我使用这个版本对吗?忽略我的脏方法line_is_comment -从第一个版本开始,除非你想玩;-)

扩展测试输入:

代码语言:javascript
复制
#Paths
A B #Path between A and B.
D C #Path between C and D.
E F
G H

输出:

代码语言:javascript
复制
 rest of line read
AB rest of line read
DC rest of line read
EF rest of line read
GH rest of line read
代码语言:javascript
复制
#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;
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56226129

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档