所以我需要打开/读取文件并找到不包含符号|
的行数。但是,我无法像strchr()
一样使用此功能:
#include <stdio.h>
#include <stdlib.h>
int countLOC(FILE *filename){
int c, nlines = 0;
filename = fopen(filename, "r");
while (c != EOF){
if (c == '\n' && strchr(c,'|') != NULL)
nlines++;
c = getc(filename);
}
printf("%d",nlines);
}
int main(){
countLOC("charc.c");
return 0;
}
程序崩溃,我不明白为什么。最初,代码只计算所有行(空行除外),但我需要检查每行是否包含|
。
答案 0 :(得分:3)
您无法将字符传递给strchr()
,它会指向char
。如果启用编译器警告,您就会知道这一点。
如果你想用当前代码计算行数,你应该读取每个字符,直到找到'\n'
为止,保持一个标志,知道是否有一个出现在行中的searc字符,然后如果至少在匹配搜索字符的字符上,则计算一行,否则不要重置该标记。
也是行
filename = fopen(filename, "r");
错误,因为fopen()
返回FILE *
个对象,它可以用来读取文件的I / O流。
您还有其他错误,请参阅此代码。希望你注意到其他错误在哪里
#include <stdio.h>
#include <stdlib.h>
int countLOC(const char *const filename)
{
int c, nlines = 0;
int found = 0;
FILE *file;
file = fopen(filename, "r");
if (file == NULL)
{
printf("failed to open %s\n", filename);
return -1;
}
while ((c = fgetc(file)) != EOF)
{
if (c == '\n')
{
nlines += (found != 0) ? 1 : 0;
found = 0;
}
found = ((c == '|') || (found != 0));
}
nlines += (found != 0) ? 1 : 0;
printf("%d", nlines);
fclose(files);
return nlines;
}
int main()
{
countLOC("charc.c");
return 0;
}
答案 1 :(得分:1)
int countLOC(const char *filename){
int c, nlines = 0, hasCh = 0;
FILE *fp = fopen(filename, "r");
while(1){
c = getc(fp);
if (c == EOF || c == '\n'){
if(hasCh)
nlines++;
if(c == EOF)
break;
hasCh = 0;
} else if(!hasCh && c == '|'){
hasCh = 1;
}
}
fclose(fp);
printf("%d\n",nlines);
return nlines;
}