-1

Fopen return NULL based on

'fopen' return a NULL

now I have one file to read and I want to output on console but it throws an error as fp return NULL here a snippet

#include<stdio.h>

int main(char argc,char **argv)
{
      if(argc < 2)
      {
            printf("Usage:\t");
            printf("Hash File path");
      }

      printf("Hash File  : %s\n", argv[1]);
      FILE *fp = fopen("argv[1]","r");
      if(fp == NULL)
      {            
            fprintf(stderr,"Can't open %s\n", argv[1]);
      }
      else
      {
           char buff[100];
           while(!feof(fp))
           {
                if(fgets(buff,100,fp) == NULL) break;
                fputs(buff,stdout);
           }
            fclose(fp);
      }
      return 0;
}

whenever I pass file Path E:\design\test.txt from the command line it always shows error report "Can't open...." like this

so the confusion is

why Fopen Failed to read from Command line?

ixnisarg
  • 117
  • 2
  • 8
  • 1
    You are stating facts. Please add a specific question to your post. – Frederik.L Sep 08 '18 at 05:29
  • 1
    Nisarg, there is still no question mark in your question, suggesting that you are not expecting any answer. The right answer at the moment is to say `ok`. New members *MUST* realize that the Q&A is to help future visitors with similar questions. During the process, you really need to think about how a visitor will ever get to your question, and nonetheless how likely the answers will be relevant. Failing to understand that is a bad experience for other members (waste of time), and for the poster (downvotes). What could really help your question is to have one, then improve the title. – Frederik.L Sep 08 '18 at 05:52
  • 1
    @Frederik.L affirmative – ixnisarg Sep 08 '18 at 06:46

1 Answers1

2

There are few issues in code. Firstly, this

FILE *fp = fopen("argv[1]","r");

is wrong. First parameter of fopen() should be just argv[1] instead of "argv[1]". For e.g

FILE *fp = fopen(argv[1],"r");
if(fp == NULL) {            
     fprintf(stderr,"Can't open %s\n", argv[1]);
     return 0; /* this you forgot, if fopen fails,then no need to proceed further */
}

Also if argc<2 is true then just wrinting printf() is not enough, you have to ask user to give correct command line input & don't let user proceed further. It should be

if(argc < 2) {
      printf("Usage:\t");
      printf("Hash File path");
      return 0; /* return from here or use exit(0) */
 }

Secondly, Read here why feof() is wrong. You can use it like

while(fgets(buff,100,fp) != NULL) { /* no need to use break */
        fputs(buff,stdout); 
}

instead of

while(!feof(fp))
{
        if(fgets(buff,100,fp) == NULL) break;
        fputs(buff,stdout);
}
Achal
  • 11,821
  • 2
  • 15
  • 37