2015-09-26 76 views
1
while((c = getc(file)) != -1) 
{ 
    if (c == ';') 
    { 
     //here I want to skip the line that starts with ; 
     //I don't want to read any more characters on this line 
    } 
    else 
    { 
      do 
      { 
       //Here I do my stuff 


      }while (c != -1 && c != '\n');//until end of file 
    } 
} 

如果行的第一个字符是分号,我可以使用getc完全跳过一行吗?使用getc读取文件并跳过以分号开头的行

+0

是的。行结尾是什么字符?你是怎么找到它的? – Davislor

+1

您的线条可以有最大长度吗?在这种情况下,为什么不简单地使用'fgets'并搜索字符串中的第一个非空格字符来查看它是否是分号,如果是则继续阅读循环。 –

+0

如果您没有阅读该行的阅读内容,您将如何找到它的结尾? –

回答

3

让我们假设用“行”表示一个字符串,直到你点击一个指定的行尾字符(这里假定为\n,不同的系统使用不同的字符或字符序列,如\r\n)。然后当前字符c是否在分号开始的行中成为一个状态信息,您需要在不同的迭代循环中维护一个状态信息。例如:

bool is_new_line = true; 
bool starts_with_semicolon = false; 
int c; 
while ((c = getc(file) != EOF) { 
    if (is_new_line) { 
    starts_with_semicolon = c == ';'; 
    } 
    if (!starts_with_semicolon) { 
    // Process the character. 
    } 
    // If c is '\n', then next letter starts a new line. 
    is_new_line = c == '\n'; 
} 

该代码仅仅是为了说明原理 - 它没有经过测试或任何东西。

+0

我明白你的想法在哪里,将尝试并让你知道,感谢分享。 – mambo

4

您的代码包含几个对-1的引用。我怀疑你认为EOF-1。这是一个常见的价值,但它只是一个负值 - 任何负值将适合int。在职业生涯开始时不要陷入坏习惯。写EOF你在哪里检查EOF(并且不要在处检查-1)。

int c; 

while ((c = getc(file)) != EOF) 
{ 
    if (c == ';') 
    { 
     // Gobble the rest of the line, or up until EOF 
     while ((c = getc(file)) != EOF && c != '\n') 
      ; 
    } 
    else 
    { 
     do 
     { 
      //Here I do my stuff 
      … 
     } while ((c = getc(file)) != EOF && c != '\n'); 
    } 
} 

注意getc()返回一个int所以c被声明为int

相关问题