2013-10-03 19 views
0

這裏的意圖是解析輸入文件,如果文件包含任何行中的時間,則需要僅從該行提取時間信息並寫入輸出文件,其餘行保持原樣。我使用fgets逐行獲取,sscanf查看所需模式,但發現seg錯誤。解析特定時間格式的字符串並將其打印到文件中C

這裏是我的代碼:

#include<stdio.h> 
int main() 
{ 
    FILE *fIn,*fOut; 
    char buffer[100]; 
    int Hr=0,Min=0,Sec=0,MSec=0; 
    fIn = fopen("dat.txt","r+"); 
    fOut= fopen("kel.txt","w+"); 
    if (fIn == NULL) { 
     printf("Can't open input file in.list!\n"); 
     exit(1); 
    } 
    while(!feof(fIn)) 
    { 
     fgets(buffer,100,fIn); 
#if 1 
     if(sscanf(buffer,"%u:%u:%u.%u",Hr,Min,Sec,MSec) ==4) 
     { 
      fprintf(fOut,"%02u:%02u:%02u.%6u",Hr,Min,Sec,MSec); 
      printf("hello"); 
      continue; 
     } 
#endif 
     fputs(buffer,fOut); 
    } 
    fclose(fIn); 
    fclose(fOut); 
} 

這裏是dat.txt的幾行:

17:48:22.618782 IP n003-000-000-000.static.ge.com > n003-000-000-000.static.ge.com: ICMP echo request, id 2105, seq 4, length 64 
     0x0000: b870 f414 033b b870 f414 0343 0800 4500 
     0x0010: 0054 0000 4000 4001 2e9c 0303 0305 0303 
     0x0020: 0303 0800 e69d 0839 0004 43bc 4a52 8d13 
     0x0030: 0300 0809 0a0b 0c0d 0e0f 1011 1213 1415 
     0x0040: 1617 1819 1a1b 1c1d 1e1f 2021 2223 2425 
     0x0050: 2627 2829 2a2b 2c2d 2e2f 3031 3233 3435 
     0x0060: 3637 
17:48:22.618817 IP n003-000-000-000.static.ge.com > n003-000-000-000.static.ge.com: ICMP echo reply, id 2105, seq 4, length 64 
     0x0000: b870 f414 0343 b870 f414 033b 0800 4500 
     0x0010: 0054 7821 0000 4001 f67a 0303 0303 0303 
     0x0020: 0305 0000 ee9d 0839 0004 43bc 4a52 8d13 
     0x0030: 0300 0809 0a0b 0c0d 0e0f 1011 1213 1415 
     0x0040: 1617 1819 1a1b 1c1d 1e1f 2021 2223 2425 
     0x0050: 2627 2829 2a2b 2c2d 2e2f 3031 3233 3435 
     0x0060: 3637 

Actualy我就嘗試寫上面的數據包text2pcap理解的形式相。我應該使用c代碼[od和hexdump不會被使用]。

+0

如果你在'sscanf'中使用'%u',你的參數應該有'unsigned int'類型,而不是'int'。 – user694733

回答

2

你需要傳遞地址其中sscanf存儲值:

if(sscanf(buffer,"%u:%u:%u.%u", &Hr, &Min, &Sec, &MSec) ==4) 
           ^^ ^ ^

此外,作爲user694733指出,如果他們是無符號(由%u暗示,使用unsigned int Hr等)。

+0

我感到很慚愧。 %u已經完成了,我正在使用%d,現在是workng。 – kelvin

+0

text2pcap表單上的任何輸入 0×0000:b870 F414 0343 b870 000000 B8 70 F4 14 03 43 B8 70 1.無前導空白 2.牛和:不應該是有 3.兩個空白空間substitue單 4兩個字節到1個字節的格式 – kelvin

相關問題