目前,我正在使用类似以下命令的命令:


  ./code output.txt


还有其他方法吗?

最佳答案

你可以使用文件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|


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

关于c - 从命令行从C中的文件读取输入测试用例,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49147444/

10-12 18:37
查看更多