2009-12-12 22 views
1

我需要閱讀格式化文件,看起來像這樣。在C中讀取格式化文件比我做的更有效嗎?

代碼:HA-RK

名稱:奧斯卡

MRTE:火車

目前我的代碼看起來是這樣的。

FILE *file; 
char unneeded[10]; 
char whitespace[2]; 
char actual[10]; 
file = fopen("scannertest.txt","r"); 
fscanf(file,"%s",unneeded); // this is the identifier and the colon (code:) 
fscanf(file,"%[ ]",whitespace); // this takes in the white space after the colon. 
fscanf(file,"%s",actual); // this is the value I actually need. 
/** 
* Do stuff with the actual variable 
**/ 
fclose(file); 

這樣對我的作品,但我不認爲在文本文件中的每一行寫三封fscanf()函數的是做到這一點的最好方式,尤其是因爲我將在循環中做後來。

我試圖做這樣的:

fscanf(file, "%s %[ ] %s",unneeded,whitespace,real); 

然而,這給了我奇怪的符號,當我試圖打印輸出。

回答

0

如果您正在尋找加速代碼的方法,您可以讀取整個文件或文件的緩衝區。根據需要讀取整個數據塊將比讀取數據更快。

然後,您可以在讀取的緩衝區上使用sscanf

+0

我嘗試使用上與fgets的sscanf()我是有這樣的。 fgets(line,20,file); sscanf(line,「%s%[]%s,unneeded,whitespace,actual); 但是,這仍然給我帶來了同樣的問題,奇怪的符號進入變量 – 2009-12-12 02:06:37

+1

聽起來更像是溢出一個緩衝區if你會看到奇怪的符號,非常確定檢查sscanf的返回值,所以你知道它實際上讀取了一些東西。 – nos 2009-12-12 02:29:40

4

%s scanf說明符已經忽略空格。如果你

scanf("%s%s", unneeded, actual) 

和輸入爲「代碼:HA-RK」,unneeded會有「代碼」和actual將「HA-RK」。

警告:scanf是一個麻煩的功能(安全使用「很難」)。如果你想更安全,指定的字符的最大數量(記住0終結),你願意接受爲每串

scanf("%9s%9s", unneeded, actual); /* arrays defined with 10 elements */ 

最好是使用fgets隨後sscanf。後

編輯閱讀註釋,以另一種答案

要記住,永遠* *檢查scanf返回值。

chk = scanf("%9s%9s", unneeded, actual); 
if (chk != 2) /* error reading data */; 
+0

非常感謝。 – 2009-12-12 03:01:27

1

在C中,文件函數使用緩衝的I/O。這意味着fscanf在每次調用時都不會碰到磁盤,因此使用3次調用而不是1次調用的性能損失應該可以忽略不計。

然而,做的最好的事情就是讓你的程序的工作,然後如果它過於緩慢措施在性能瓶頸和解決這些第一。試圖猜測哪些代碼段會導致性能問題是不值得的。

0

我是一個偶爾錯過C編碼的病人。我寫了出來,似乎想些:test.txt的

內容

Code: HARK 
Name: Oscar 
MRTE: Train 

內容的text.c的

#include <stdio.h> 

#define MAX_LEN 256 

int main(void) 
{ 
    FILE *file; 
    char str_buf[MAX_LEN + 1]; // One extra byte needed 
          // for the null character 
    char unneeded[MAX_LEN+1]; 
    char actual[MAX_LEN+1]; 


    file = fopen("test.txt","r"); 

    while(fgets(str_buf, MAX_LEN + 1, file) != NULL) 
    { 
    sscanf(str_buf, "%s%s", unneeded, actual); 
    printf("unneeded: %s\n", unneeded); 
    printf("actual: %s\n", actual); 
    } 

    return 0; 
} 

輸出的編譯代碼:

unneeded: Code: 
actual: HARK 
unneeded: Name: 
actual: Oscar 
unneeded: MRTE: 
actual: Train 
1

你代碼不起作用,因爲

不會做同樣的事情,

fscanf(file,"%s %[ ] %s", unneeded, whitespace, actual); 

它在功能上等同

fscanf(file,"%s%[ ]%s", unneeded, whitespace, actual); // No spaces in fmt string 

HTH

相關問題