我想读取Ubuntu中文件的行数。对于我的代码,我使用的是CodeBlocks。C - 为什么在fopen(filename,“r”)之后fp == NULL是true?
这是我所做的代码。
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,这是真的。
我把文字放在与我的主文件夹相同的文件夹中。可执行文件位于Projectfolder/bin/Debug中。
词是这样的:
"albatros",
"olifant",
"kantklos",
"robijn",
"internet"
的最终目标是,以填补的文件的话的话阵列,而不使用的#include“字”。
可能是文件未找到,可能是您没有读取权限,请使用[stat]检查问题(http://man7.org/linux/man-pages/man2/stat.2。 HTML)。 –
这就是为什么你应该说; if(fp == NULL){perror(“Ups”);返回-1; }'('perror'给你一个理由,而'-1'或者其他负值是OK方式来调用函数调用失败。) – Morpfh
它的话。我有权限阅读文件 – Jasper