cfilenullfopen

C - Why is fp == NULL true after fopen(filename, "r")?


I am trying to read the number of lines of a file in Ubuntu. For my code I'm using CodeBlocks.

This is the code I've made.

int countlines()
{
  // count the number of lines in the file called filename
  FILE *fp = fopen("words", "r");
  int ch=0;
  int lines=0;

  if (fp == NULL){
    return 0;
  }

  lines++;
  while(!feof(fp))
  {
    ch = fgetc(fp);
    if(ch == '\n')
    {
        lines++;
    }
  }
  fclose(fp);
  return lines;
}

If I call countlines(), the return value is a 0, that is because he checks if fp==NULL, and that is true.

I placed words in the same folder as my main. The executable file is in Projectfolder/bin/Debug.

Words looks like this:

"albatros",
"olifant",
"kantklos",
"robijn",
"internet"

The final goal is to fill an array with the words of the file words, without using #include "words".


Solution

  • Check what the working directory is set to. It might not be pjt/bin/Debug. Also, try specifying full path to the file.