fscanf函数统计文件的单词个数

来源:互联网 发布:郑州支点软件 编辑:程序博客网 时间:2024/05/21 17:22
如果我们想将数字相关类型(int,float类型等)读/写文件显然是不可以的。例如我们想在某文件中写入float类型3.5,则不能使用fputc()/fputs()。这时我们可以使用我们熟悉的printf()/scanf()函数以及它们的同族函数fprintf()/fscanf()实现数据的格式化读/写。
函数scanf()、fscanf()、sscanf()
需要头文件:#include<stdio.h>
函数原型:int scanf(const char *format,...);
          int fscanf(FILE *fp,const char *format,...);
 int sscanf(char *buf,const char *format,...);
函数参数:format:输入的格式
          fp:待输入的流
 buf:待输入的缓冲区
函数返回值:成功:读到的数据个数
            失败:EOF
函数printf()、fprintf()、sprintf()
需要头文件:#include<stdio.h>
函数原型:int printf(const char *format,...);
          int fprintf(FILE *fp,const char *format,...);
 int sprintf(char *buf,const char *format,...);
函数参数:format:输出的格式
          fp:待输出的流
 buf:待输出的缓冲区
函数返回值:成功:输出的字符数

            失败:EOF


#include<stdio.h>
#include<stdlib.h>
#define N 128
int main(int argc, const char *argv[])
{
FILE *fp;
if (argc < 2)
{
printf("users: ./a.out + filename\n");
return -1;
}
if (NULL == (fp = fopen(argv[1], "r")))
{
perror("open failed");
return -1;
}
int total = 0;
char buff[N] = {0};
while(EOF != fscanf(fp, "%s", buff))
{
total++;
}
printf("total = %d\n", total);
return 0;
}

原创粉丝点击