C -为什么fopen(filename,“r”)后面的fp == NULL为true?

ef1yzkbh  于 2023-06-05  发布在  其他
关注(0)|答案(3)|浏览(149)

我试图在Ubuntu中读取文件的行数。我的代码使用CodeBlocks。
这是我做的代码。

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;
}

如果我调用countlines(),返回值是0,这是因为他检查fp==NULL是否为真。
我把单词和我的主文件夹放在同一个文件夹里。可执行文件位于项目文件夹/bin/Debug中。
单词看起来像这样:

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

最终目标是用文件单词的单词填充数组,而不使用#include“words”。

fwzugrvs

fwzugrvs1#

检查工作目录的设置。它可能不是pjt/bin/Debug。另外,请尝试指定文件的完整路径。

bxfogqkk

bxfogqkk2#

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

fp被检查为NULL,因为fopen返回指针,如果成功,它将是非NULL,所以如果fp == NULL,则文件打开不成功。这就是为什么程序无法继续,只能返回。

twh00eeo

twh00eeo3#

嗯!!!可能是没有指定“words”的文件扩展名。除此之外,我找不到程序的其他错误。

相关问题