写入文件而不是stdout

时间:2012-03-05 05:18:11

标签: stdout

我正在用C.编写程序。该程序打印出当前目录中的文件。 我想要一些文本文件中的输出不在控制台上。 我的计划是: -

int main()
{

        system("ls");
        return 0;
}

提前致谢!!!

3 个答案:

答案 0 :(得分:2)

由于您已经在使用system(),并且这已经取决于平台,只需使用shell的重定向功能 - 即。,

system("ls > /home/you/thefile");

答案 1 :(得分:1)

这是您写入文件的方式,只需将输出替换为文件中的内容即可。 正如另一个人提到的那样,你可以把它传递给一个文件。

FILE *ofp;
char outputFilename[] = "out.txt";

ofp = fopen(outputFilename, "w");

if (ofp == NULL) {
  fprintf(stderr, "Can't open output file %s!\n",
          outputFilename);
  exit(1);
}

fprintf(ofp, "ls");
fclose(ofp);

答案 2 :(得分:0)

还有另一个将stdout重定向到文件的功能

###stdio.h
###FILE *freopen(const char *filename, const char *mode, FILE *stream);

    int main()
    {
      char outputFilename[] = "out.txt";
      freopen(filename, "w", stdout)

        system("ls");
        return 0;
    }

重定向后到stdout的所有输出都将写入文件“out.txt”

相关问题