【问题标题】:reading input testcases from a file in C from command line从命令行从 C 文件中读取输入测试用例
【发布时间】:2018-08-15 06:59:32
【问题描述】:

目前我正在使用如下命令:

./code output.txt

还有其他方法吗?

【问题讨论】:

  • 这样做有什么问题这种方式???
  • 有很多不同的方法,你的要求是什么?

标签: c command


【解决方案1】:

您可以使用文件 I/O 操作,fopen()fclose() 以及您使用的任何文件版本从 stdin...fscanf()fgetc()fgets() 读取。

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

int main () {
   char str1[10], str2[10], str3[10];
   int year;
   FILE * fp;

   fp = fopen ("file.txt", "w+");
   fputs("We are in 2012", fp);

   rewind(fp);
   fscanf(fp, "%s %s %s %d", str1, str2, str3, &year);

   printf("Read String1 |%s|\n", str1 );
   printf("Read String2 |%s|\n", str2 );
   printf("Read String3 |%s|\n", str3 );
   printf("Read Integer |%d|\n", year );

   fclose(fp);

   return(0);
}

输出:

Read String1 |We|
Read String2 |are|
Read String3 |in|
Read Integer |2012|

如果您想让代码足够通用以接受来自多个不同文件的输入,您可以将文件名指定为命令行选项。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-05
    • 2010-11-16
    • 2021-10-29
    • 1970-01-01
    相关资源
    最近更新 更多