[英]output to a file using command line
我正在编写一个程序,该程序应该能够接受命令行参数。 基本上,用户在调用程序时必须能够通过命令提示符指定文件名。 即程序应该能够接受一个参数,例如: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);
}
所以我注意到了几件事...
看看这段代码是否有助于解决您的问题,(我还在其中扔了一个fprintf()来向您展示如何写入文件)。 干杯!
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]);
}
//saftey check
if(argv[1])
{
filename = argv[1];
//open the specified file
outputFile = fopen(filename, "w");
fprintf(outputFile, "blah blah");
//write to file
fclose(outputFile );
}
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.