2017-10-15 75 views
-3

我想問問你,如何從文件中使用C語言閱讀:閱讀contet,FOPEN禁止

your_program <file.txt 

cat file.txt 
Line one 
Line two 
Line three 

我有類似的東西,但它不管用。非常感謝

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

int main(int argc, char *argv[]) 
{ 
    int vstup; 
    input = getchar(); 


    while(input != '\n') 
     printf("End of line!\n"); 
    return 0; 
} 
+0

您希望從程序中獲得什麼輸出?實際產出是多少?你意識到你做了一個無限循環,因爲'input'在你第一次分配給它之後永遠不會改變,對吧? –

+1

以及這不工作? –

+0

您只讀取了文件中的一個字符。 –

回答

0

你可以使用freopen()使stdin指輸入文件而不是鍵盤。

這可以用於輸入或輸出重定向。

在你的情況,做

freopen("file.txt", "r", stdin); 

現在stdin與文件相關file.txt,當你閱讀使用像scanf()功能,你實際上是從file.txt閱讀。

freopen()將關閉舊流(這裏是stdin)「否則,該函數的行爲就像fopen()」。如果發生錯誤,它將返回NULL。所以你最好檢查freopen()返回的值。

查看更多about freopen()herehere

正如其他人已經指出的那樣,您發佈的代碼可能會有一個無限循環,因爲input的值在循環內永遠不會改變。

0

編譯/中提出的代碼鏈接到一些文件,讓調用可執行文件:run

運行下面的建議代碼時,輸​​入文件

./run < file.txt 

這裏重定向「標準輸入」被提出的代碼:

     // <<-- document why a header is being included 
#include <stdio.h> // getchar(), EOF, printf() 
//#include <stdlib.h> <<-- don't include header files those contents are not used 

int main(void) // <<-- since the 'main()' parameters are not used, 
        //  use this signature 
{ 
    int input;  // <<-- 'getchar()' returns an integer and EOF is an integer 
    while((input = getchar()) != EOF) // <<-- input one char per loop until EOF 
    { 
     if('\n' == input)    // is that char a newline? 
     { 
      printf("End of line!\n"); // yes, then print message 
     } 
    } 
    return 0; 
} // end function: main <<-- document key items in your code