[英]output to a file using command line
I am writing a program that should be able to take command line parameters. 我正在编写一个程序,该程序应该能够接受命令行参数。 Basically, the user must be able to specify a file name through command prompt while calling the program. 基本上,用户在调用程序时必须能够通过命令提示符指定文件名。 ie the program should be able to take in a parameter like: doCalculation -myOutputfile.txt. 即程序应该能够接受一个参数,例如:doCalculation -myOutputfile.txt。 where doCalculation is the name of my program and myOutputfile is the file I want my results written to (ie output the results of my calculations to the specified file name). 其中doCalculation是我的程序的名称,而myOutputfile是我要将结果写入的文件(即,将计算结果输出到指定的文件名)。
So far I can call my function through the command prompt. 到目前为止,我可以通过命令提示符调用函数。 I am not sure how to get my program to write to the filename specified (or create this file if it does not exist already). 我不确定如何使程序写入指定的文件名(如果尚不存在,则创建此文件)。
My code is as follows: 我的代码如下:
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);
}
So a couple things I noticed... 所以我注意到了几件事...
See if this code helps solve your problem, (I also tossed a fprintf() in there to show you how you can write to the file). 看看这段代码是否有助于解决您的问题,(我还在其中扔了一个fprintf()来向您展示如何写入文件)。 Cheers! 干杯!
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.