我想计算一个c文件的行,忽略有注释或空行的行,我想出了以下代码,但我的字符串(char指针)只返回三个字符而不是整行:
FILE* pf = NULL;
char *chaine;
int count=0;
int com=0;
pf=fopen("test.c","r+");
while(!feof(pf))
{
if(com%2==0)
count++;
fgets(&chaine, sizeof(chaine),pf);
if(&chaine=='\n' || &chaine==' ' || strstr(&chaine, "//") != NULL)
{
count--;
}
if(strstr(&chaine, "//*") != NULL || strstr(&chaine, "*//") != NULL)
{
com++;
}
printf("The line %d have the following string : %s\n",count,&chaine);
}
//printf("The number of lines est : %d", count);
特别感谢@Michael Walz的答案,我发现我的指针有问题。在我重新调整我的if条件后,行计数器工作正常,这是工作代码:
#include <stdio.h>
#include <string.h>
int main(void)
{
FILE* pf = NULL;
char chaine[1000];
int count = 0;
int com = 0;
pf = fopen("test.c", "r");
while (1)
{
if (com % 2 == 0 | strstr(chaine, ";//") != NULL)
count++;
if (fgets(chaine, sizeof(chaine), pf) == NULL)
break;
if (chaine[0] == '\n' || chaine[0] == "" || strstr(chaine, "//") != NULL)
{
count--;
}
if (strstr(chaine, "/*") != NULL)
{
com++;
}
if (strstr(chaine, "*/") != NULL)
{
com++;
}
}
fclose(pf);
printf("The file have %d line code", count);
}
答案 0 :(得分:1)
你可能想要这个:
#include <stdio.h>
#include <string.h>
int main(void)
{
FILE* pf = NULL;
char chaine[1000];
int count = 0;
int com = 0;
pf = fopen("test.c", "r");
if (pf == NULL) // we abort if the file cannot be opened
{
printf("File cannot be opened\n");
return 1;
}
while (1) // see link below
{
if (com % 2 == 0)
count++;
if (fgets(chaine, sizeof(chaine), pf) == NULL)
break; // if fgets returns NULL we are presumably at the end of the file
if (chaine[0] == '\n' || chaine[0] == ' ' || strstr(chaine, "//") != NULL)
{
count--;
}
if (strstr(chaine, "//*") != NULL || strstr(chaine, "*//") != NULL)
{
com++;
}
printf("The line %d have the following string : %s\n", count, chaine);
}
}
这是未经测试的代码,可能存在错误。
另请阅读:Why is “while ( !feof (file) )” always wrong?。
我还强烈建议您阅读有关字符串的章节以及处理C教科书中指针的章节。