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. 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).
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). 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;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.