title: C - Reading files passed as command line argument
body: <p>I am a newbie to C coding, and I am working on a project. There is a problem I couldn't solve. I am trying to count the words in a given text file (passed as an argument), but every time I got the result "file can't open"</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  
  int main(int argc, char *argv[]) {
  
    FILE *fptr;
    char ch;
    int w = 0;
  
    /* char filename[15];
    printf("Enter the filename to be opened \n");
    scanf("%s", filename);
    open the file for reading
    fptr = fopen(filename, "r"); */
  
    /* argc must be 2 for correct execution */
    if (argc != 2) {
      /* Assume that argv[0] is the program name */
      printf("usage: %s, &lt;file_name&gt;", argv[0]);
      return 0;
    }
  
    fptr = fopen(argv[1], "r");
    if (fptr == NULL) {
      printf("can't open file");
    }
    else {
      ch = fgetc(fptr);
      while (ch != EOF) {
        if (ch == ' ' || ch == '\n') {
          w++;
        }
        ch = fgetc(fptr);
      }
      printf("\nWords in a file are=%d", w);
      printf("\n");
    }
    fclose(fptr);
  }
  </code></pre>
  
  <p>the output should be the number of words in the file, but each time I tried it I got the result can't open file</p>
  
  <pre><code>./CountWords  test.txt
  Can't open file
  </code></pre>
  
  <p>When I tried to change by asking the user to enter the file name (as what I put in comments and I just do it to know where is the error) it works, and I got the number of words. But this doesn't help me because am working on project that needs to count the number of words in a file passing as command line argument.</p>
  
  <pre><code>char filename[15];
      printf("Enter the filename to be opened \n");
        scanf("%s", filename);
      open the file for reading 
      fptr = fopen(filename, "r");
  </code></pre>
  
  <p>That means the code works but the problem is only in reading files passed as command line arguments. I searched for similar problems and tried their solutions, and I wrote an existing code from other tutorials that read files as command line argument but the problem is the same.</p>
  
  <p>I use Linux, and I tried to use different files in different paths but the problem wasn't fixed.   </p>