关键点
- fgets()是碰到换行符‘\n’,就认为是一行;
- 但是有换行符,不一定就是一行;
- 如果是一行,换行符‘\n’后面,一定有结束符‘\0’
- n=strlen()返回的n正好是结束符下表,n-1是换行符下标
- str=fgets()后,判断一下str[strlen(str)]是不是等于‘\0’
代码
#include <stdio.h>
#include <string.h>
int get_file_length(const char *file);
int main(int argc, const char *argv[])
{
if(argc <2)
{
printf("usage:%s <file name or path>\n",argv[0]);
return -1;
}
printf("total length is %d\n",get_file_length(argv[1]));
return 0;
}
int get_file_length(const char *file)
{
int count = 0;
int str_len = 0;
const int N=100;
char buf[N];
FILE *fp;
if((fp = fopen(file,"r")) == NULL)
{
perror("fopen");
return -1;
}
while((fgets(buf,N,fp)) != NULL)
{
if(buf[strlen(buf)] == '\0')
count ++;
}
if(fclose(fp) == EOF)
{
perror("fclose");
return -1;
}
return count;
}
运行结果