简体   繁体   English

为什么C中的linecount没有工作?

[英]Why doesn't my linecount in C work?

I'm trying to read a text file but before that I want to know how many elements I'm going to read. 我正在尝试阅读一个文本文件但在此之前我想知道我要阅读的元素数量。 So I need to count the lines of a text file. 所以我需要计算文本文件的行数。 So far, I have this: 到目前为止,我有这个:

int getLinecount (char *file) 
{
    int ch, count = 0;
    FILE *fp = fopen(file, "r");
    if(fp == NULL)
    {
        return -1;
    }
    while((ch = fgetc(fp)) != EOF)
    {
        if (ch == '\n'); 
        {
            count++;
        }
    }
    fclose(fp);
    return count;
}

This worked pretty fine. 这很好用。 I have changed nothing about the text file and still it prints 130,000 though the file only has 10,000 lines. 我没有对文本文件做任何改变,但仍打印130,000,尽管文件只有10,000行。 The only thing I wrote in my main is: 我在我的主要内容中唯一写的是:

linecount = getLinecount("...");

I am really curious where the error is. 我真的很好奇错误在哪里。 Also, is there a better option of getting the linecount? 此外,是否有更好的选择获得linecount?

You have a trailing semicolon ; 你有一个尾随的分号; after your if statement. 在你的if语句之后。 Then, the block is always executed: 然后,始终执行块:

{
    count++;
}

Change 更改

if (ch == '\n'); 

to: 至:

if (ch == '\n')

Trailing semi-colon after the if : remove it. if之后尾随分号:将其删除。 With the trailing semi-colon the code is equivalent to: 使用尾部分号代码相当于:

if (ch == '\n') {}
count++;

meaning that count is incremented for every iteration of the loop (every char in the file). 意味着对于循环的每次迭代(文件中的每个char ), count都会递增。

you have trailing semicolon to delete after if 你已经尾随分号删除后if

and for reading files, better use this code : 并且为了阅读文件,更好地使用此代码:

while((fgets(blahblahblah)) != NULL) {
  counter++;
}

一切都很好,除了分号( ; ),应该从行中删除

if (ch == '\n')

Apart from the ; 除了; issue mentioned by others, an alternative solution can be found in this post as he explains why he does things the way he does. 在其他人提到的问题上,可以在这篇文章中找到另一种解决方案,因为他解释了为什么他按照他的方式做事。

You might want to consider the OS you are using to create and view this file. 您可能需要考虑用于创建和查看此文件的操作系统。

Copied from PHP Echo Line Breaks : PHP Echo Line Breaks复制:

  • '\\n' is a linux/unix line break '\\ n'是linux / unix换行符
  • '\\r' is a classic mac line break [OS X uses the above unix \\n] '\\ r'是一个经典的mac换行符[OS X使用上面的unix \\ n]
  • '\\r'+'\\n' is a windows line break '\\ r'+'\\ n'是一个Windows换行符

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM