1

I'm working on a program and it's something I can't understand. I have a main function with arguments:

int main(int argc, const char *argv[]){
    FILE *file;
    file=fopen(argv[1], "r");

    if( file == NULL )
    {
      perror("Error while opening the file.\n");
      exit(EXIT_FAILURE);
    }

How do I read the argv[1] file. When I compile it error shows up as Invalid argument. How do I get the file to open so I can print the things it's hiding? I'm using Code Blocks.

Racil Hilan
  • 24,690
  • 13
  • 50
  • 55
marblapas
  • 25
  • 4

1 Answers1

3

The argv[1] refers to the first argument passed by the user on the command line. argv[0] refers to the file itself. So in your case, the program will open the file passed as the first argument.

./myprogram myfilename.txt

Moreover, you have a few issues with the program itself.

    #include <stdio.h>  /* Library needed for input/output*/    
    #include <stdlib.h> /* needed for the exit calls*/

    int main(int argc, const char *argv[]){
        FILE *file;
        file=fopen(argv[1], "r");

        if( file == NULL )
        {
            perror("Error while opening the file.\n");
            exit(1);
        }

        return 0;
        }

This obviously doesnt do much right now but it will get argv1 open. Also, I changed exit(EXIT_FAILURE) to exit(1). They are mostly synonymous but exit(1) doesn't require a compiler flag (-std=c99). EXIT_FAILURE is considered more portable - EXIT_FAILURE vs exit(1)? - but again for simplicity, I changed it to exit(1).

Community
  • 1
  • 1
wbt11a
  • 798
  • 4
  • 12
  • Thanks. But I stills don't really understand how I should open the file. For now it's called main.c and it's in a project in Code Blocks. Can I just run it from the cmd or am I missing something again? – marblapas Mar 14 '14 at 12:31
  • No problem. I think what you need to do is go to Projects -> Set Program Arguments, and set the name of the program you want as argv[1]. – wbt11a Mar 14 '14 at 12:34
  • Just a note: `EXIT_FAILURE` does not require any compiler flags--just `#include `. Adding `-std=c99` to the compile command line just tells the compiler to warn about things that weren't part of that standard--leaving it off tells the compiler that we don't care about complying with a particular standard, so don't warn about anything that the compiler recognizes as valid, including extensions. Additionally, `EXIT_FAILURE` was already defined in C89, so I don't know of any set of flags that would cause the compiler to warn about its use. – laindir Mar 14 '14 at 13:49