Search code examples
cargvargc

About `argv` and opening a file with command line


I have this code:

#include <stdio.h>

int main ( int argc, char *argv[] )
{    
     FILE *file;
     int x;

     if ( argc != 2 )
           printf( "Use: %s file name", argv[0] );
     else {
            if ((file=fopen( argv[1], "r" ))== 0 ) 
            printf( “Couldn't open the file.\n" );
             else {
                          while (( x = fgetc( file ) ) != EOF)  printf( "%c", x );
                          fclose( file );
              }
      }
      return 0;
}

Now, having this code, how do I execute a file from terminal (that is on the pic as well as my configuration of NetBeans). https://i.sstatic.net/6WRh3.png


Solution

  • First, better replace your statement (in your program above)

    printf( “Couldn't open the file.\n" );
    

    with

    perror(argv[1]);
    

    then, simply compile your program in your terminal, e.g. type there a shell command similar to

    gcc -Wall -g mysource.c -o myprog
    

    (Read more about invoking GCC: the -Wall option asks for nearly all warnings and is very useful -so never miss it-; you could even add -Wextra to get even more warnings; the -g is asking for DWARF debugging information in the ELF executable and enables you to use later gdb)

    assuming your source code is in a file named mysource.c in the current working directory (use pwd command to query that current directory, ls -al to list it, and cd builtin command to change it)

    at last, run your program as

    ./myprog sometestfile.txt
    

    You might want to use the debugger. Read first about GDB, and try perhaps

    gdb ./myprog
    

    (I am guessing you are on Linux or some other POSIX compliant operating system, and using GCC compiler)

    Read more about perror(3), command line interface, shells, globbing, glob(7), PATH variable

    Later, you'll want to have some bigger program of yours made in several translation units, having some common header file (to be #included in all of them). Then you'll use a builder like GNU make. You could use a good editor like emacs, some version control like git, etc...

    (you might realize that NetBeans is not very useful, because you can have even better developing comfort with your own collection of tools; having the freedom to choose your tools is worthwhile!)

    PS. Perhaps replace printf( "%c", x ); with the shorter and more efficient putchar(x); ...