簡體   English   中英

運行 C 程序以讀取終端中的文本文件

[英]Run a C program to read a text file in terminal

我是 C 編程的初學者。 我正在做一個作業,要求我使用帶有 C 文件和 a.txt 文件的命令作為 MACOS 終端中的輸入,並使用 C 程序讀取文件的內容,例如“./cfile text.txt ”。

我是否必須包括以下內容:

FILE *ptr = fopen("text.txt", "r");

在 C 文件中?

如果沒有,我怎樣才能獲得“text.txt”文件作為 C 文件的輸入?

使用 argc 和 argv。 在 shell 中執行您的程序,編寫“./program text.txt”,它會工作。 然后你只需要寫

int main(int argc, int *argv[])
{
      FILE *ptr;
      //rest of variables
      if (argc != 2) write(1, "Did not put a file name to read.\n", strln("Did not put a file name to read.\n"));
      ptr = fopen(argv[1], "r");
      //rest of program
}

暫無
暫無

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

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