使用C对ASCII文件中的行进行计数 [英] Count lines in ASCII file using C

查看:79
本文介绍了使用C对ASCII文件中的行进行计数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想计算ASCII文本文件中的行数.我认为最好的方法是计算文件中的换行符:

I would like to count the number of lines in an ASCII text file. I thought the best way to do this would be by counting the newlines in the file:

for (int c = fgetc(fp); c != EOF; c = fgetc(fp)) {  /* Count word line endings. */
    if (c == '\n') ++lines;
}

但是,我不确定这是否能解释所有MS Windows和Linux的最后一行.那是如果我的文本文件如下所示完成,没有显式换行符,是否在那里进行了编码,还是应该在for循环之后添加额外的 ++ lines; ?

However, I'm not sure if this would account for the last line on all both MS Windows and Linux. That is if my text file finishes as below, without an explicit newline, is there one encoded there anyway or should I add an extra ++lines; after the for loop?

cat
dog

然后,如果文件末尾有 明确的换行符怎么办?还是只需要跟踪先前读取的值来测试这种情况?

Then what about if there is an explicit newline at the end of the file? Or do I just need to test for this case by keeping track of the previously read value?

推荐答案

如果没有换行符,则不会生成换行符.C会告诉您确切的内容.

If there is no newline, one won't be generated. C tells you exactly what's there.

这篇关于使用C对ASCII文件中的行进行计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆