fopen() returns NULL while running program from Comand Line

112 Views Asked by At

Any of my C programmes utilizing fopen() run perfectly from IDE or Windows environment, but fail when opened from Command Line (cmd.exe), as fopen("r") keeps returning NULL pointer. The files do exist and have no permission restrictions. So the programms DO run from Command Line, but with error (null pointer) as soon as they encounter fopen() in the code.

int main(int argc, char *argv[])
 {
  FILE *fr, *fw;
  int j;

  if(argc==1)
   {
     vypis_navodu(argv[0]); // function call
   }

  if(argc==2)
   {     
      if ((fr=fopen(argv[1], "r")) == NULL) // returns NULL from CMD 
          {
           printf("\nunable to open %s\n", argv[1]); 
           return 1;    
          }

SOLUTION USING THE FULL PATH TO FILE:

int main(int argc, char *argv[])
{
FILE *fr, *fw;
char path[100] = "C:\\folder\\"; // path to the folder
int j;

if(argc==1)
 {
  vypis_navodu(argv[0]);
 }


if(argc==2)
 {   
    if ((fr=fopen(strcat(path, argv[1]), "r")) == NULL) // works o.k.
      {
        printf("\nunable to open %s\n", argv[1]);
        return 1;   
      }
1

There are 1 best solutions below

2
Harith On

From the man page:

The fopen(), fdopen(), and freopen() functions may also fail and set errno for any of the errors specified for the routine malloc(3).

The fopen() function may also fail and set errno for any of the errors specified for the routine open(2).

You may use perror or strerrror to print out an error message.

The perror() function produces a message on standard error describing the last error encountered during a call to a system or library function.

Here's an example:

#include <errno.h>
#include <stdlib.h>
#include <stdio.h>

int main(int argc, char *argv[]) 
{
    /* argument checking here... */

    FILE *fp;

    errno = 0;
    fp = fopen(argv[1]), "r");
    if (!fp) {
        perror("fopen");
        return EXIT_FAILURE;
    }
    return EXIT_SUCCESS;
}