2016-03-24 40 views
-1

我是新編程的C語言編程人員,我試圖編寫一個程序來讀取名爲input的文件的上下文。爲什麼我的C程序不工作?從文件中讀取

#include <stdio.h> 
#include <stdlib.h> 

int main() 
{ 
    char ch; 
    FILE *in; 
    in = fopen("input","r"); 
    printf("The contents of the file are\n"); 
    fscanf(in,"%c",&ch); 
    printf("%c",ch); 
    fclose(in); 
    return 0; 
} 
+3

請描述的內容'輸入文件,以及實際上發生了什麼行爲,以及您期望什麼而不是。 –

+0

輸入文件只是隨機文本測試例如,你好世界 –

+0

所以你回答了3個問題提出的第一個... –

回答

0

試試這個 -

char text[100]; 
fp=fopen(name,"r"); 
fgets(text,sizeof(text),fp); //99 is maximum number of characters to be printed including newline, if it exists 
printf("%s\n",text); 
fclose(fp); 
+1

「100是要打印的字符的最大數量」否一個字節用於終止空字符,因此最大爲99個字符,包括換行符(如果存在)。 – MikeCAT

+0

謝謝,我會做一個編輯。 –

+1

也使用幻數不好,使用'fgets()'的行應該是'fgets(text,sizeof(text),fp);'添加錯誤檢查會使代碼更好。 – MikeCAT

1

您的代碼讀取只是文件的第一個字符。沒有循環來讀取整個文件。這是你的意圖嗎?

另外,檢查文件打開是否成功。輸入文件名稱是「輸入」嗎?

-1

你應該使用這樣的:

#include <stdio.h> 
#include <stdlib.h> 

int main() 
{ 
    char ch; 
    FILE *in; 

    /*Don't forget the extension (.txt)*/ 
    if(in = fopen("input.txt","r") == NULL);  
    { 
     printf("File could not be opened\n"); 
    } 
    else         
    { 
     printf("The contents of the file are\n"); 
     /*I assume that you are reading char types*/ 
     fscanf(in,"%c",&ch);     

     /*Check end-of-file indicator*/ 
     while(!feof(in))      
     { 
      printf("%c",ch); 
      fscanf(in,"%c",&ch); 
     } 
    } 

    fclose(in); 
    return 0; 
} 

你應該牢記驗證文件是否打開與否,它始終是一個很好的做法。

+1

最好不要測試'feof'。 [見這裏](http://stackoverflow.com/questions/5431941/why-is-while-feof-file-always-wrong)的解釋。 –

0

假設文件input的內容是:

Hello World 

你可以試試下面的代碼:

#include <stdio.h> 
#include <stdlib.h> 

int main() 
{ 
    char ch; 
    FILE *in; 
    in = fopen("input","r"); 
    printf("The contents of the file are\n"); 
    while(fscanf(in, "%c", &ch) != EOF) 
    { 
     printf("%c",ch); 
    } 
    fclose(in); 
    return 0; 
} 

輸出:

The contents of the file are 
Hello World 
相關問題