问题
I want my C program to ask the user to type the name of the file they want to open and print the contents of that file to the screen. I am working from the C tutorial and have the following code so far. But when I execute it, it doesn't actually allow me to enter the file name. (I get the 'press any button to continue', I am using codeblocks)
What am I doing wrong here?
#include <stdio.h>
int main ( int argc, char *argv[] )
{
printf("Enter the file name: \n");
//scanf
if ( argc != 2 ) /* argc should be 2 for correct execution */
{
/* We print argv[0] assuming it is the program name */
printf( "usage: %s filename", argv[0] );
}
else
{
// We assume argv[1] is a filename to open
FILE *file = fopen( argv[1], "r" );
/* fopen returns 0, the NULL pointer, on failure */
if ( file == 0 )
{
printf( "Could not open file\n" );
}
else
{
int x;
/* Read one character at a time from file, stopping at EOF, which
indicates the end of the file. Note that the idiom of "assign
to a variable, check the value" used below works because
the assignment statement evaluates to the value assigned. */
while ( ( x = fgetc( file ) ) != EOF )
{
printf( "%c", x );
}
fclose( file );
}
}
return 0;
}
回答1:
If you want to read user input from a prompt, you would use the scanf()
function. To parse command line parameters, you would type them at the command line, as in:
myprogram myfilename
rather than just typing
myprogram
and expecting to be prompted. myfilename
would be in the argv
array when your program starts.
So, start by removing the printf( "Enter the file name:" )
prompt. The filename would be in argv[ 1 ]
assuming you entered it as the first parameter after myprogram
on your command line.
回答2:
This will read from stdin the filename. Perhaps you only want to do this if the filename is not supplied as a part of the command line.
int main ( int argc, char *argv[] )
{
char filename[100];
printf("Enter the file name: \n");
scanf("%s", filename);
...
FILE *file = fopen( filename, "r" );
回答3:
You are mixing up command line arguments with user input.
When you use command line arguments, you execute the program and pass the arguments at the same time. For example:
ShowContents MyFile.txt
In contrast, when you read user input, you first execute the program, then provide the file name:
ShowContents
Enter the file name: MyFile.Ttxt
Your program already reads the first argument argv[1]
and treats it as the name of the file to open. To have the program read user input, do something like this:
char str[50] = {0};
scanf("Enter file name:%s", str);
Then the file name will be in str
, instead of argv[1]
.
回答4:
It's because your IDE is not passing the filename argument to your program. Take a look at this question on stackoverflow.
来源:https://stackoverflow.com/questions/9449295/opening-a-file-from-command-line-arguments-in-c