[英]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.