gpt4 book ai didi

c - C 中的文件行计数器

转载 作者:行者123 更新时间:2023-11-30 20:59:24 25 4
gpt4 key购买 nike

我想计算 c 文件的行数,忽略有注释或空行的行,我想出了以下代码,但我的字符串(字符指针)仅返回三个字符而不是整行:

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);
}

最佳答案

您可能想要这个:

#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 教材中处理字符串的章节和处理指针的章节。

关于c - C 中的文件行计数器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47650764/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com