簡體   English   中英

如何在C中讀取通過stdin傳遞的文件

[英]How to read a file passed through stdin in C

我想將文本文件傳遞給像這樣的C程序./program < text.txt 我在SO上發現像這樣傳遞的參數不會出現在argv[] ,而是出現在stdin 如何在stdin中打開文件並閱讀?

您可以直接讀取數據,而無需打開文件。 stdin已經打開。 如果沒有特殊檢查,您的程序將不知道它是文件還是來自終端或管道的輸入。

您可以使用read或使用stdio.h函數通過其文件描述符0訪問stdin 如果函數需要FILE * ,則可以使用全局stdin

例:

#include <stdio.h>
#define BUFFERSIZE (100) /* choose whatever size is necessary */

/* This code snippet should be in a function */

char buffer[BUFFERSIZE];

if( fgets(buffer, sizeof(buffer), stdin) != NULL )
{
    /* check and process data */
}
else
{
    /* handle EOF or error */
}

您也可以使用scanf讀取和轉換輸入數據。 此函數始終從stdin讀取(與fscanf相反)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM