C 读取目录中具有相同扩展名的文件并计算其行数
我的代码有这个问题。我一直在尝试打开具有相同扩展名的文件,并读取目录中文件的行数。 下面是我所做的:C 读取目录中具有相同扩展名的文件并计算其行数,c,eof,eol,C,Eof,Eol,我的代码有这个问题。我一直在尝试打开具有相同扩展名的文件,并读取目录中文件的行数。 下面是我所做的: #include <stdio.h> #include <stdlib.h> #include <dirent.h> #include <math.h> #include <string.h> #include <ctype.h> int countLines(char name[]); int main() {
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <math.h>
#include <string.h>
#include <ctype.h>
int countLines(char name[]);
int main()
{
struct dirent *de;
DIR *dr=opendir(".");
char check[16]=".nkt";
int i;
char name[64];
int count=0;
if(dr==NULL)
{
printf("Didn't open!");
return 0;
}
while((de=readdir(dr))!=NULL)
{
if((strstr(de->d_name, check))!=NULL)
{
strcpy(name, de->d_name);
countLines(name);
}
}
closedir(dr);
return 0;
}
int countLines(char name[])
{
FILE *fp;
fp=fopen(name,"r");
char ch;
int lines=0;
while(!feof(fp))
{
ch=fgetc(fp);
if(ch=='\n')
{
lines++;
}
}
fclose(fp);
printf("%d\n", lines);
}
即使每个文件有54行。
非常感谢您的帮助。
另外,扩展名是.nkt您显示的countLines函数正在陷入几个陷阱
返回int而不是char。它这样做是为了能够返回文件结束状态,而不考虑所有其他可能的字符值。一个简单的字符不能做到这一点
使用feof识别文件结尾失败,因为只有在最后一次读取到文件结尾后,才设置EOF指示符。因此,使用feof控制的循环通常迭代一次到多次
对此进行了详细讨论
文本文件的最后一行不一定带有文件结束指示符,但您很可能仍然希望计算该行。需要应用特殊逻辑来涵盖这种情况
解决上述所有问题的函数的可能实现可能如下所示:
#include <stdio.h>
/* Returns the number of lines inside the file named file_name
or -1 on error. */
long count_lines(const char * file_name)
{
long lines = 0;
FILE * fp = fopen(file_name, "r"); /* Open file to read in text mode. */
if (NULL == fp)
{
lines = -1;
}
else
{
int previous = EOF;
for (int current; (EOF != (current = fgetc(fp)));)
{
if ('\n' == current)
{
++lines;
}
previous = current;
}
if (ferror(fp)) /* fgetc() returns EOF as well if an error occurred.
This call identifies that case. */
{
lines = -1;
}
else if (EOF != previous && '\n' != previous)
{
++lines; /* Last line missed trailing new-line! */
}
fclose(fp);
}
return lines;
}
关于问题评论部分中关于不同线端指标的讨论:
文本文件的行尾指示符在不同的UNIX平台上的实现方式不同:'\n'与Windows:\r\n与
为了解决这个问题,C库函数默认以文本模式打开一个文件。如果以这种方式打开,C实现会注意将每行的结尾作为单个“\n”字符返回,即所谓的新行字符。请注意上述第3项。最后一行可能根本没有行结束指示器。这段代码对我来说很好。您使用的是哪种操作系统?请尝试\r而不是\n@RoyaGhasemzadeh我正在使用Windows10Pro@RoyaGhasemzadeh现在它在这里打印出0'sSee:
#include <stdio.h>
/* Returns the number of lines inside the file named file_name
or -1 on error. */
long count_lines(const char * file_name)
{
long lines = 0;
FILE * fp = fopen(file_name, "r"); /* Open file to read in text mode. */
if (NULL == fp)
{
lines = -1;
}
else
{
int previous = EOF;
for (int current; (EOF != (current = fgetc(fp)));)
{
if ('\n' == current)
{
++lines;
}
previous = current;
}
if (ferror(fp)) /* fgetc() returns EOF as well if an error occurred.
This call identifies that case. */
{
lines = -1;
}
else if (EOF != previous && '\n' != previous)
{
++lines; /* Last line missed trailing new-line! */
}
fclose(fp);
}
return lines;
}