0
我正在编写一个应该能够执行命令行参数的程序。 基本上,用户必须能够在调用程序时通过命令提示符指定文件名。即程序应该能够接受如下参数: doCalculation -myOutputfile.txt。其中doCalculation是我的程序的名称,myOutputfile是我希望将结果写入到的文件(即将我的计算结果输出到指定的文件名)。使用命令行输出到文件
到目前为止,我可以通过命令提示符调用我的函数。我不确定如何让我的程序写入指定的文件名(或者如果它不存在,则创建该文件)。
我的代码如下:
int main(int argc, char *argv[])
{
FILE* outputFile;
char filename;
// this is to make sure the code works
int i = 0;
for (i = 0; i < argc; i++) {
printf("argv[%d] = %s\n", i, argv[i]);
}
//open the specified file
filename= argv[i];
outputFile = fopen("filename", "r");
//write to file
fclose(outputFile);
}
你甚至试过阅读C库的文档吗?阅读fopen函数的模式参数说明。 – dbenham 2013-02-16 20:42:32
一个简单的Google搜索“c写入一个文件示例”产生的绰绰有余的例子。 – dbenham 2013-02-16 20:45:32
正如博C.建议,您需要添加一行,如'fprintf(outputFile,“blah blah”);'实际写入您打开的文件。 – 2013-02-16 22:13:18