Opening a file from command line arguments in C

I want my C program to ask the user to enter the name of the file they want to open and print the contents of this file on the screen. I am working from a C tutorial and still have the following code. But when I execute it, it actually does not allow me to enter a file name. (I get "press any button to continue", I use code blocks)

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; } 
+6
source share
4 answers

If you want to read user input from a prompt, you must use the scanf() function. To analyze command line options, you must enter them at the command line, for example:

 myprogram myfilename 

not just typing

 myprogram 

and expect to be offered. myfilename will be in the argv array when your program starts.

So, start by removing the printf( "Enter the file name:" ) prompt. The file name will be in argv[ 1 ] if you enter it as the first parameter after myprogram on the command line.

+4
source

This will read from the stdin file name. Perhaps you want to do this only if the file name is not specified as 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" ); 
+5
source

You mix 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 instance:

 ShowContents MyFile.txt 

In contrast, when you read user input, first run the program, and then specify the file name:

 ShowContents Enter the file name: MyFile.Ttxt 

Your program already reads the first argument to argv[1] and treats it as the name of an open file. For the program to read user input, do the following:

 char str[50] = {0}; scanf("Enter file name:%s", str); 

Then the file name will be in str instead of argv[1] .

+4
source

This is because your IDE does not pass a file name argument to your program. Take a look at this fooobar.com/questions/732333 / ....

+2
source

Source: https://habr.com/ru/post/909370/


All Articles