fgets统计文件行数
来源:互联网 发布:w7搜索不到网络打印机 编辑:程序博客网 时间:2024/06/14 10:20
需要头文件:#include<stdio.h>
函数原型:char *gets(char *s)
char *fgets(char *s,int size,FILE *stream)
函数参数:s:存放输入字符的缓冲区地址
size:输入的字符串长度
stream:输入文件流
函数返回值:成功:s
失败或读到文件尾:NULL
在Linux的内核man手册中,对gets()函数的评价是:"Never use gets(). Because it is impossible to tell without knowing the data in advance how many characters gets() will read, and because gets() will continue to store characters past the end of the buffer, it is extremely dangerous to use. It has been used to break computer security. Use fgets() instead."简单来说gets()的执行逻辑是寻找该输入流的'\n'并将'\n'作为输入结束符,但是若输入流数据超过存储空间大小的话会覆盖掉超出部分的内存数据,因此gets()函数十分容易造成缓冲区的溢出,不推荐使用。而fgets()函数的第二个参数指定了一次读取的最大字符数量。当fgets()读取到'\n'或已经读取了size-1个字符后就会返回,并在整个读到的数据后面添加'\0'作为字符串结束符。因此fgets()的读取大小保证了不会造成缓冲区溢出,但是也意味着fgets()函数可能不会读取到完整的一行(即可能无法读取该行的结束符'\n')。
int main(int argc, const char *argv[])
{
FILE * fp;
if (argc < 2)
{
printf("too few arguements :user ./a.out + filename\n");
return 0;
}
printf("%s %s\n", argv[0], argv[1]);
if (NULL == (fp = fopen(argv[1], "r")))
{
perror("open failed");
return 0;
}
char s[N] = {0};
int total = 0;
while(NULL != fgets(s, N-1, fp))
{
if ('\n' == s[strlen(s)-1])
{
total++;
}
}
printf("total = %d\n", total);
fclose(fp);
return 0;
}
- fgets统计文件行数
- 标准I/O:分别用fgetc与fputc,fgets与fputs统计文件的行数
- Linux统计文件行数
- Linux统计文件行数
- Linux统计文件行数
- 统计文件行数
- Linux统计文件行数
- 统计文件行数
- Linux统计文件行数
- Linux统计文件行数
- Linux统计文件行数
- Linux统计文件行数
- 统计文件的行数
- 统计文件行数
- 统计文件内容行数
- Linux统计文件行数
- Linux统计文件行数
- hadoop统计文件行数
- java中的Date和Calendar类的使用.还有math类种的函数使用
- 我爱代码之自学的乐趣
- sdnu1104数据排序
- <单调栈/悬线法>codevs 2491 玉蟾宫 1159 最大全0子矩阵
- Hive安装
- fgets统计文件行数
- 我为什么选择c程序?
- LintCode 95-验证二叉查找树
- Linux中断驱动示例
- NOIP 2002 普及组 复赛 过河卒
- CodeForces 337D Book of Evil(双向dfs)
- 关于爬虫——前言
- Linux入门推荐书籍
- 答案错误