-
Command line args
First time using command line args in C, and can't get it to work. Here's what I got:
this should get the one and only command line argument, which is a filename, then it calls openFile with that. If there is no command line arguments, it gets it from within the program.
Code:
if(argc == 2){
if(openFile(argv[1]) == 1){
countWords();
showResults();
closeFile();
}
else{
printf("Does not exist\n");
return EXIT_FAILURE;
}
}
else{
getFileName();
if(openFile(fileName) == 1){
countWords();
showResults();
closeFile();
}
else{
printf("Does not exist\n");
return EXIT_FAILURE;
}
}
and here is my open file
Code:
int openFile(char* filename){
/*Open the file*/
if((inFile = fopen(fileName, "r")) == NULL){
return 0;
}
return 1;
}
The code for getting the filename within the program works fine, it just tells me the file does not exist whenever it gets run with the command line arg. Any suggestions?
-
does the filename have spaces or anything? try using quotes around it on the command line.
also i assume "inFile" is declared globally, and as FILE *?
*EDIT* how are you declaring argc and argv?
-
Yeah, you have a global variable with a near identical name to your parameter
Code:
int openFile(char* filename){
/*Open the file*/
if((inFile = fopen(fileName, "r")) == NULL){
return 0;
}
return 1;
}
The parameter you pass is being ignored.
Since you don't refer to the global var when using the command line, you end up with the situation which you have now.
Better get rid of inFile being a global as well.
You may as well get rid of openFile, and actually do something like
Code:
if( (inFile=fopen(argv[1],"r")) != NULL){
because your openFile() is adding almost no value
-
-
This one works for me.
static FILE *open_file ( char *file, char *mode )
{
FILE *fp = fopen ( file, mode );
/* "r" open for reading */
/* "w" create for writing, discard previous contents */
/* "a" append, open or create for writing */
/* "r+" open for update */
/* "w+" create for update, discard previous contents */
/* "a+" append, open or create for update */
if ( fp == NULL ) {
printf("Unable to open %s for %s\n", file, mode);
perror ( "Unable to open file" );
exit ( EXIT_FAILURE );
}
return fp;
}
-
What's the point? And do you really want to exit your program just because you can't open a file? I suppose it's ok for logging purposes, but as a general use tool, why not just use fopen as is?
Quzah.