2014-01-29 170 views
0

特定文本的兩行之間的文件和提取行我想提取文本是在[曲棍球]之間,並從以下文件[曲棍球做]:閱讀用C

sport.txt

[HOCKEY] 
a=10 
b=20 
c=30 
d=45 
[done with HOCKEY] 
[SOCCER] 
a=35 
b=99 
c=123 
d=145 
[done with SOCCER] 

用下面的代碼,我就能檢查線[曲棍球]但我無法拍攝到一號線[曲棍球]之間的位置和最後一行[曲棍球做]

#include<stdio.h> 
int main() 
{ 
FILE *infile; 
char start, end; 
char *sport="[]"; 
char line_buffer[BUFSIZ]; /* BUFSIZ is defined if you include stdio.h */ 
int line_number,i; 
infile = fopen("sport.txt", "r"); 
printf("Opened file for reading\n"); 
line_number = 0; 
while (fgets(line_buffer, sizeof(line_buffer), infile)) { 
    ++line_number; 
    /* note that the newline is in the buffer */ 
    if (line_buffer=="[HOCKEY]") 
    { 
    start=line_buffer; 
    printf("Found start %s",start); 
    } 
     if (line_buffer=="[done with HOCKEY]") 
    end=line_buffer; 

    while(start<end){ 
    printf("%c",start); 
    start++; 
    system("PAUSE"); 
    } 
} 
return 0; 
} 
+0

究竟是什麼問題? – herohuyongtao

+0

需要學習如何處理C中的字符串。 – BLUEPIXY

回答

1
  1. 第一行是[HOCKEY]後的第一行。並且

  2. 最後一行是[done with HOCKEY]之前的最後一行。

所以你需要的是一行一行地讀取文件。當您讀取[HOCKEY]時,您正在接近您所需的實際數據,並開始讀取並存儲下一行的數據。繼續此步驟,直到您閱讀[done with HOCKEY]並停止。

0
int count = 0; 
char found_it = 0; 
char *wordStart = "[HOCKEY]"; 
char *wordStop = "[done with HOCKEY]"; 
int charCount = strlen(wordStart); 
while((c = getc(fptr)) != EOF){ 
    if(c == wordStart[count]){ 
     count++; 

     if(count == charCount){printf("Found [HOCKEY] \n"); found_it = 1; break;} 
    } 
    else{ 
     count = 0; 
    } 
} 

if(!found_it){printf("Did not find [HOCKEY] \n"); return 0;} 

count = 0; found_it = 0; 
charCount = strlen(wordStop); 
while((c = getc(fptr)) != EOF){ 
    printf("%c", c); 
    if(c == wordStop[count]){ 
     count++; 

     if(count == charCount){found_it = 1; break;} 
    } 
    else{ 
     count = 0; 
    } 
} 

if(!found_it){printf("Did not find [done with HOCKEY] \n");} 
return 0; 
0
#include <stdio.h> 
#include <string.h> 

int main(){ 
    FILE *infile; 
    fpos_t start, end, pre_pos; 
    char line_buffer[BUFSIZ]; /* BUFSIZ is defined if you include stdio.h */ 
    //char line_buffer[128]; // BUFSIZ : I do not know if there is a large enough 

    infile = fopen("sport.txt", "r"); 
    if(infile) 
     printf("Opened file for reading\n"); 
    else { 
     perror("file open"); 
     return -1; 
    } 
    fgetpos(infile, &pre_pos); 
    end = start = pre_pos; 
    while (fgets(line_buffer, sizeof(line_buffer), infile)) { 
     if (strcmp(line_buffer, "[HOCKEY]\n")==0){ 
      fgetpos(infile, &start); 
     } else if (strncmp(line_buffer, "[done with HOCKEY]", 18)==0){//18 == strlen("[done with HOCKEY]"); 
      end=pre_pos; 
      break; 
     } 
     fgetpos(infile, &pre_pos); 
    } 
    fsetpos(infile, &start); 
    while(start<end){ 
     printf("%c", fgetc(infile)); 
     fgetpos(infile, &start); 
    } 
    fclose(infile); 
    system("PAUSE"); 
    return 0; 
}