-5

I have a program that should take the file's name from command line using argc and argv. Printing argv[1] and argv[2] show me the exactly names I passed, but passing argv[1] and argv[2] as parameters to open the files in another function just show the error line I put if can't open the file.
My main:

int main(int argc, char* argv[])
{
    if (argc != 4) 
    {
        puts("Incorrect number of parameters.");
        return 1;
    }
    else
    {
    Image *a, *b;

    a = OpenFile(argv[1]);
    b = OenFile(argv[2]);

    } /* else */
    return 0;
} /* main */

The function OpenFile will return a struct filled with information from the file. Here's the first part of the function:

Image *OpenFile(char* name)
{
    FILE* f = fopen(name, "r");
    Image* imagem;
    int temp, i, cont, data[MAX];
    char aux[2];

    if(f == NULL)      
    {
        puts("Error opening file.");
        return NULL;
    } /* if */
    ...
}

I'm passing the correct names but I receive the "Error opening file." line for each file I try to open.

Edit: It's giving me "No such file or directory", but I copied the files to the directory where the .exe is placed. It's not the first time I use the file's name from command line, but it's the first time I pass as parameters to another function.

Ing
  • 1
  • 2
  • From the little information you have provided, the logical conclusion appears to be that your program encountered an error while trying to open the file. – John Bollinger Apr 09 '16 at 13:05
  • Please, provide the names of files you are passing to the program. We don't know how you are compiling code and where the executable is placed after build process. Maybe your output directory does not contain files that you are trying to read. – Kamil Apr 09 '16 at 13:10
  • Naturally, you are passing a fully-qualified, absolute file specification that is totally unambiguous? – Martin James Apr 09 '16 at 13:13
  • The name of the files are: teste_cena.pgm, teste_objeto.pgm and saida.txt (the output file, but I'm not using yet). – Ing Apr 09 '16 at 13:44

1 Answers1

3

From fopen man page:

RETURN VALUE

Upon successful completion fopen(), fdopen() and freopen() return a FILE pointer. Otherwise, NULL is returned and errno is set to indicate the error.

So You could change:

 if(f == NULL)      
{
    puts("Error opening file.");
    return NULL;
} /* if */

With:

 if(f == NULL)      
{
    perror("fopen");
    return NULL;
} /* if */

And you ll get a pretty descriptive message on the reason fopen failed.

You should include errno.h in order to use perror

sestus
  • 1,875
  • 2
  • 16
  • 16