fgetc从点跳到新线

时间:2013-12-06 22:16:03

标签: c fgetc

我正在尝试让fgetc读取文件并跳过某个指示符直到换行。这似乎是一个简单的问题,但我找不到任何文档。

以下是我的问题示例:

read this in ; skip from semicolon on to new line

我对解决方案的最佳猜测是读取整个文件,并为每行使用strtok跳过;到最后一行。显然这是非常低效的。有什么想法吗?

*我需要使用fgetc或fgetc之类的东西来解析文件中的字符

3 个答案:

答案 0 :(得分:1)

最简单的方法是读取整行,然后截断;是否

char buffer[1024], * p ;

if ( fgets(buffer, sizeof(buffer), fin) )
{
  if (( p= strchr( buffer, ';' ))) { *p = '\0' ; }  // chop off ; and anything after
  for ( p= buffer ; ( * p ) ; ++ p )
  {
    char c= * p ;
    // do what you want with each character c here.
  }
}

执行读取时,缓冲区最初将包含:

  

“读取此内容;从分号跳到新行\ n \ 0”

在行中找到;并在其中粘贴'\0'后,缓冲区如下所示:

  

“在\ 0中读取此内容从分号跳到新行\ n \ 0”

因此for循环从r开始,并在第一个\0停止。

答案 1 :(得分:0)

鉴于需要使用fgetc(),那么你可能应该将所有内容都回显到该行的第一个分号,并禁止从分号到行尾的所有内容。我顺便指出getc()在功能上等同于fgetc(),并且由于此代码即将从标准输入读取并写入标准输出,因此使用getchar()和{{}是合理的。 1}}。但规则是规则......

putchar()

如果您没有C99和#include <stdio.h> #include <stdbool.h> int main(void) { int c; bool read_semicolon = false; while ((c = fgetc(stdin)) != EOF) { if (c == '\n') { putchar(c); read_semicolon = false; } else if (c == ';') read_semicolon = true; else if (read_semicolon == false) putchar(c); /* else suppressed because read_semicolon is true */ } return 0; } ,则可以使用<stdbool.h>int0代替1,{{1}分别和bool。如果您愿意,可以使用false

答案 2 :(得分:0)

//Function of compatible fgets to read up to the character specified by a delimiter.
//However file stream keep going until to newline.
//s : buffer, n : buffer size
char *fgets_delim(char *s, int n, FILE *fp, char delimiter){
    int i, ch=fgetc(fp);

    if(EOF==ch)return NULL;
    for(i=0;i<n-1;++i, ch=fgetc(fp)){
        s[i] = ch;
        if(ch == '\n'){
            s[i+1]='\0';
            break;
        }
        if(ch == EOF){
            s[i]='\0';
            break;
        }
        if(ch == delimiter){
            s[i]='\0';//s[i]='\n';s[i+1]='\0'
            while('\n'!=(ch = fgetc(fp)) && EOF !=ch);//skip
            break;
        }
    }
    if(i==n-1)
        s[i] = '\0';
    return s;
}