【发布时间】:2019-10-13 07:17:16
【问题描述】:
我的代码有这个问题。我一直在尝试打开具有相同扩展名的文件并读取目录中文件的行数。 所以,这就是我所做的:
#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);
}
我得到的结果总是这样:
2
2
2
即使每个文件都有 54 行。 希望能得到一些帮助。 PS。扩展名为 .nkt
【问题讨论】:
-
这段代码对我来说很好用。您使用的是哪个操作系统?
-
尝试 \r 而不是 \n
-
@RoyaGhasemzadeh 我使用的是 Windows 10 专业版
-
@RoyaGhasemzadeh 现在打印出 0