读入文本文件并显示除所有空行和注释外的每一行的 C 程序

标签 c tokenize

基本上,我需要读入一个文本文件,并且只打印整行,不包括以注释或空格开头的任何内容。我很难忽略评论之后的内容,或者基本上忽略 ; 之后的内容,直到 \n 字符。这将指示该行的结尾。

我认为这段代码可以工作,但它仍然在注释后打印,

 char* t=strtok(line,"\n ,.; ");
          while(t != NULL ) {
            if(t == ";"){
                t = strtok(NULL," ");
                while(t != NULL && t!="\n") {
                t = strtok(NULL, "");
              }
            }
            else
            {
                printf("%s\n",t);
                t = strtok( NULL, "\n ,.; \n");
            }
          }
        }

这是完整的代码:

int main()
{

char line [5000];
FILE *fp;

fp=fopen("gt.txt", "r");
if (fp == NULL)
 perror ("error opening file");
else{
  while(fgets (line, sizeof (line), fp)){
    char* t=strtok(line,"\n ,.; ");
      while(t != NULL ) {
        if(t == ";"){
            t = strtok(NULL," ");
            while(t != NULL && t!="\n") {
            t = strtok(NULL, "");
          }
        }
        else
        {
            printf("%s\n",t);
            t = strtok( NULL, "\n ,.; \n");
        }
      }
    }
  }
fclose(fp);
return(0);
}

这是我打印的内容,也是下面用作我的文本文件的内容:

hello                                                                                        
goodbye 
error                                                                                        
interesting                                                                                  
comment                                                                                      
wonderful

分号是文本文件中真正的分号:

hello
goodbye


(semicolon) error
(semicolon) error

interesting (semicolon) comment

wonderful

提前致谢

最佳答案

only print full lines excluding anything that begins (with) a comment or whitespace

OP 的 if(t == ";"){ 不是所需的函数。 @Craig Estey .请务必启用所有警告以节省时间。

将指针 char *t";" 进行比较,并且可能 OP 想要比较指向的字符串的内容或者可能比较 *t 是一个 ';'


有时 state machine是很好的简单方法。跟踪行尾。当开始一个新行时,previous == '\n',测试它是否是一个空白行。

#include <ctype.h>
#include <stdio.h>
#define COMMENT_CHAR (';')

int main(void) {
  FILE *fp = fopen("gt.txt", "r");
  if (fp == NULL) {
    perror("error opening file");
    return EXIT_FAILURE;
  }

  bool blank_the_line = false;
  int previous = '\n';
  int ch;

  while ((ch = fgetc(fp)) != EOF) {
    if (previous == '\n') {
      blank_the_line = isspace(ch) || ch == COMMENT_CHAR;
    }
    if (!blank_the_line) {
      fputc(ch, stdout);
    }
    previous = ch;
  }

  fclose(fp);
  return EXIT_SUCCESS;
}

注意:没有行长限制。

关于读入文本文件并显示除所有空行和注释外的每一行的 C 程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52864879/

相关文章:

java - Apache Solr 6.6.1 乌尔都语语言的数字映射

c++ - 改变参数值和数量——这是合法的 C++ 吗?

c - 为什么按回车不返回 '\n' 到 getch()?

python - 使用 nltk 标记 unicode

objective-c - 为什么 cStringUsingEncoding : returns const char * instead of char *?

c - malloc 结构中的结构数组

parsing - 代码的上下文敏感标记化

java分割字符串

c - 为什么这种不正确的编译和链接会导致我的 C 源文件被删除?

c - Julia ccall 的不一致行为