2012-12-27 21 views
0

分隔比方說,我有一個txt文件:搜索在C多個單詞,並顯示信息後,他們用逗號

日期:11/11/11

設備:Boxster的

狀態:好

我想讓我的代碼搜索一個單詞(說設備:),並顯示該單詞(Boxster)後的信息。到目前爲止,我的代碼工作只搜索一個單詞。我怎樣才能修復代碼,以便它可以搜索2或3個單詞,並顯示他們後面的信息?

這將是更有益的,如果我可以表現在以下格式的信息:

的Boxster,11/11/11,不錯。

這是我的代碼,在此先感謝!

#include <stdio.h> 
#include <string.h> 
#include <stdlib.h> 
int main() { 

    char file[100]; 
    char c[100]; 

    printf ("Enter file name and directory:"); 
    scanf ("%s",file); 

    FILE * fs = fopen (file, "r") ; 
    if (fs == NULL) 
    { 
     puts ("Cannot open source file") ; 
     exit(1) ; 
    } 

    FILE * ft = fopen ("book5.txt", "w") ; 
    if (ft == NULL) 
    { 
     puts ("Cannot open target file") ; 
     exit(1) ; 
    } 

    while(!feof(fs)) { 
     char *Data; 
     char *Device; 
     char const * rc = fgets(c, 99, fs); 

     if(rc==NULL) { break; } 

     if((Data = strstr(rc, "Date:"))!= NULL) 
      printf(Data+7); 

     if((Data = strstr(rc, "Device:"))!=NULL) 
      printf(Device+6); 
    } 

    fclose (fs) ; 
    fclose (ft) ; 

    return 0; 

} 
+3

這不是C++。 – 0x499602D2

+0

1)feof()錯誤2)'printf(Data + 5);'應該是'printf(Data + 7);'3)什麼是「dateL:」? 4)strtok或strspn + strcspn可能會訣竅。 – wildplasser

回答

0

注意一些改變printf和FGETS您可以使用一個邏輯或||進行多次檢查一個字符串。

嘗試:

char rc[120]={0x0}; 
while(fgets(rc, sizeof(rc), fs)!=NULL) { 
     char *Data; 
     char *Device; 

     if((Data = strstr(rc, "Date:"))!= NULL) 
      printf("%s\n", &Data[7]); 

     if((Device = strstr(rc, "Device:"))!=NULL || 
      (Device = strstr(rc, "String:"))!=NULL || 
      (Device = strstr(rc, "foo:"))!=NULL) 
      printf("%s\n", &Device[6]); 
    } 

當你瞭解關於搜索,你可能能夠實現對搜索的正則表達式,如果你的系統支持,在C.

相關問題