![](/img/trans.png)
[英]How do I make a program in C that will read ad print specific lines from a file?
[英]C program to read specific lines from a file
我正在尝试制作一个程序,该程序将对文件中的行进行计数并将其他行引用为特定行(即,不应以#开头的行进行计数)
while(fgets(tempstring,sizeof(tempstring),fptr)){
lines++;
if(tempstring[0] != '#' || tempstring[0]!='\n'|| tempstring[0]!=' '){
++count;
}
现在我在这里做错了什么?
另外我还注意到,第一次调用fgets时,会得到∩
作为tempstring[0]
的输出,这是为什么呢?
您的条件始终为真-您想使用&&
或否定整体||
:
if (tempstring[0] != '#' && tempstring[0]!='\n' && tempstring[0]!=' ')
要么
if(!(tempstring[0] == '#' || tempstring[0] == '\n' || tempstring[0] == ' '))
这是等效的。 请注意,您可以删除if
完全的,因为true
在C是一样的1
:
count += (tempstring[0] != '#' && tempstring[0]!='\n' && tempstring[0]!=' ');
另请注意,取决于sizeof(tempstring)
, fgets
可能会或可能不会给您行的开头。 如果tempstring
对于文件中的整个字符串来说不够长,则您的调用可能会从另一个字符串的中间产生一个字符串,从而导致错误的行为。 这很难修复,因为现在您需要一个循环来检查从fgets
返回的字符串的最后一个字符为'\\n'
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.