2012-11-21 38 views
2

我可以让我的程序打印出我的文本文件,但是如何才能使它打印出特定的行?就像是否有几行内容是相同的,并且我希望在运行该程序时将它们打印出来?从顺序文件中选择性地打印输出行

#include <stdio.h> 

int main (void){ 
    static const char filNavn[] = "test.txt"; 
    FILE *fil = fopen(filNavn, "r"); 
    if (fil != NULL){ 
     char line [ 256 ]; 
     while(fgets(line, sizeof(line), fil) != NULL){ 
      fputs(line, stdout); 
     } 
     fclose(fil); 
    } 
    else{ 
     perror(filNavn); 
    } 
    return 0; 
} 
+0

我该怎么做呢? :) – Winkz

+0

我推荐你随机访问文件,他们比顺序好得多http://stackoverflow.com/questions/13438941/comparing-and-checking-columns-in-two-files/13463644#13463644 –

+0

是的几个信息,就像我想要所有名称为“bob”的行,例如,如果你跟着我? – Winkz

回答

1

基本上你需要做的是:

  1. 存储在变量插槽line(你说的44个字符)。
  2. 使用string.h函数库中的strstr函数来查找字符串line的位置,其中字符串"2 - 0"存在,如果不存在,则返回NULL指针。
  3. 如果指针不是NULL,那么您可以打印该行。
  4. 该循环将继续,直到fil指针达到end of the file

    if (fil != NULL){ 
    
        /* 44 characters because you said that the data is stored in strings of 44. */ 
        /* And I will think that you inputed the data correctly. */ 
        char line [ 44 ]; 
    
        /* While you don't reach the end of the file. */ 
        while(!feof(fil)){ 
    
         /* Scans the "slot" of 44 characters (You gave it that format)*/ 
         /* starting at the position of the pointer fil and stores it in fil*/ 
         fscanf(fil, %44s, line); 
    
         /* If the result of the internal string search (strstr) isn't null. */ 
         /* Print the line.*/ 
         if(strstr(line, "2 - 0") != NULL){ 
          printf("%s\n", line) 
         } 
    
         /* Else keep the loop....*/ 
        } 
    
        fclose(fil); 
    } 
    
+1

@Michael Jensen:你也可以使用** regex.h **中的函数来创建一个更强大的搜索选择的行。如果这些行遵循格式良好的模式(如果它们是正则表达式 - 请参阅:[正则表达式 - 维基百科](http://en.wikipedia.org/wiki/Regular_expression)),您可以识别行中的字段并使用他们进行比较:例如:只打印BA获胜或RUIN分数大于1的行。(这里我假设分数2和0分别与BA和RUIN相关)。 – Guarita

+0

我仍然有问题的程序,我可以找到与你给我的信息的某些行,并感谢你! :)但我想输入它我的自我和该程序找到我需要的线路,但不能得到它的工作,任何想法如何帮助我与此?如果你想当然:) – Winkz

-1

只要把你的条件读/打印循环中:

包括

int main (void) 
{ 
    static const char filNavn[] = "test.txt"; 
    FILE *fil = fopen(filNavn, "r"); 
    if (fil != NULL) 
    { 
     char line [ 256 ]; 
     while(fgets(line, sizeof line, fil) != NULL) 
     { 
      // if this line is interesting (eg, has something "the same") 
       fputs(line, stdout); 
     } 
     fclose(fil); 
    } 
    else 
    { 
     perror(filNavn); 
    } 
    return 0; 
} 
+0

你说什么可以评论,为什么你不给他的代码是一个有效的答案? –

+0

不太确定如何做到这一点,如果一句话或? – Winkz

+0

是的,一个“if”声明 - 就像我在评论中所建议的那样。当然,情况究竟取决于你在找什么,OP没有说什么。 –