【问题标题】:Run a C program to read a text file in terminal运行 C 程序以在终端中读取文本文件
【发布时间】:2020-05-09 15:51:09
【问题描述】:

我是 C 编程的初学者。我正在做一个作业,要求我在 MACOS 的终端中使用带有 C 文件和 .txt 文件的写入命令作为输入,并使用 C 程序读取文件的内容,例如“./cfile text.txt” ”。

我是否必须包括以下内容:

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

在 C 文件中?

如果没有,我怎样才能将“text.txt”文件作为 C 文件的输入?

【问题讨论】:

  • 是否还没有很多关于如何做到这一点的信息?

标签: c file terminal


【解决方案1】:

使用 argc 和 argv。在编写“./program text.txt”的shell中执行你的程序,它就会工作。然后你只需要写

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
}

【讨论】:

  • 我复制了您的代码,但无法成功编译程序。我被要求使用“gcc cfile.c -o xxx”进行编译,但终端显示 ```“将参数传递给参数 '__filename' 这里 FILE *fopen(const char *_restrict __filename, const char * ++retri. ..".```我该如何解决这个问题?谢谢。
猜你喜欢
  • 2020-01-16
  • 2011-09-26
  • 2020-01-24
  • 2018-05-12
  • 1970-01-01
  • 1970-01-01
  • 2020-12-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多