2010-02-22 70 views
2

我如何讀取輸入一個字符串,同時調用另一個函數C.我想這會工作,但我的輸出掛起:同時從文件中讀取一個字符串用C

#define BUFFMT "%255" 
#define LINE_LEN 256 
#define START_COUNT 1 

// filename is declared in the main file elsewhere. I know the file opens since I tried an //old method I use to read one line at time using fgets, but I didn't know how to do one //string at a time. Thanks. 
FILE *OpenFile(const char *fileName) 
{ 
    FILE *fptr; 
    if ((fptr = fopen(fileName, "r")) == NULL) { 
     fprintf(stderr, "Error opening file %s, exiting...", fileName); 
     exit(EXIT_FAILURE); 
    } 
    return fptr; 
} 

LIST *CreateList(FILE *fp) 
{ 
    char buf[LINE_LEN]; 

    while (scanf(BUFFMT"s", buf) != EOF) { 
     printf("%s: \n", buf); 
    } 
} 
+0

你如何在主程序中調用這些函數? – 2011-11-03 01:02:44

回答

4

scanf()要從終端讀取,所以它會等待您輸入您的輸入。改爲使用fscanf(fp, BUFFMT"s", buf)

2

嘗試這不是你的scanf函數:

fgets (buf, sizeof (buf), fp) 
0

您是否嘗試過使用fgets()

fgets()

fgets()從流中讀取長度爲1的字符 並將它們存儲在緩衝區中。 與fgets()存儲空字符 (「\ 0」)的最後一個字符後讀取 入緩衝區,並返回「緩衝」 如果一切正常,或 錯誤或文件結尾NULL。

相關問題