淡然者

fscanf

fscanf编辑

函数名: fscanf
功 能: 从一个流中执行格式化输入,fscanf遇到空格和换行时结束,注意空格时也结束。这与fgets有区别,fgets遇到空格不结束。
中文名
文件格式输入
外文名
File Scan Format
类    别
计算机软件
简    述
C语言中基本的文件操作
函数名
fscanf
FILE *stream
文件指针

1一般形式编辑

函数名: fscanf
功 能: 从一个流中执行格式化输入,fscanf遇到空格和换行时结束,注意空格时也结束。这与fgets有区别,fgets遇到空格不结束。
用法:
1
intfscanf(FILE*stream,constchar*format,[argument...]);
FILE *stream:文件指针;
char *format:格式字符串;
[argument...]:输入列表。
例如:
1
2
3
4
5
6
7
8
9
FILE* fp;
 
char a[10];
 
int b;
 
double c;
 
fscanf(fp , "%s %d %lf" , a , &b , &c);
返回值:整型,成功读入的参数的个数

2格式字符说明编辑

常用基本参数对照:
%d:读入一个十进制整数.
%i :读入十进制,八进制,十六进制整数,与%d类似,但是在编译时通过数据前置或后置来区分进制,如加入“0x”则是十六进制,加入“0”则为八进制。例如串“031”使用%d时会被算作31,但是使用%i时会算作25.
%u:读入一个无符号十进制整数.
%f %F %g %G : 用来输入实数,可以用小数形式或指数形式输入.
%x %X: 读入十六进制整数.
%o': 读入八进制整数.
%s : 读入一个字符串,遇空字符‘\0'结束。
%c : 读入一个字符。无法读入空值。空格可以被读入。
附加格式说明字符表修饰符说明
L/l 长度修饰符 输入"长"数据
h 长度修饰符 输入"短"数据
示例说明
如果要求从标准输入中输入一串字符串和一个整型数,那么参数“%s%d”表示什么呢?默认情况下,在终端上(这里假设程序为控制台应用程序)输入第一个参数的值的时候敲下回车,则在第二行输入的为第二个参数值,采用这种输入方法那么格式字符的形式就无关紧要了。
这里要特殊说明的是如果参数在同一行给出,那么格式字符的参数与终端的输入会有什么关系。举个例子:如果格式字符为“%s+%d”,那么参数的输入就应该为 string + integer。

3程序例编辑

例一

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <stdlib.h>
#include <stdio.h>
int main(void)
{
int i;
printf("Input an integer:");
/*read an integer from the standard input stream*/
if(fscanf(stdin,"%d",&i))
printf("The integer read was:%d\n",i);
else
{
fprintf(stderr,"Error reading an\
integer from stdin.\n");
exit(1);
}
return0;
}
返回EOF如果读取到文件结尾。

例二

附:MSDN中例子
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
/*FSCANF.C:This program writes formatted data to afile.It then uses fscanf to read the various databackfromthefile.*/
#include <stdio.h>
FILE *stream;
int main(void)
{
long l;
float fp;
char s[81];
char c;
stream=fopen("fscanf.out","w+");
if(stream==NULL)
printf("The file fscanf.out was not opened\n");
else
{
fprintf(stream,"%s%ld%f%c","a-string",
65000,3.14159,'x');
/*Set pointer to beginning of file:*/
fseek(stream,0L,SEEK_SET);
/*Readdatabackfromfile:*/
fscanf(stream,"%s",s);
fscanf(stream,"%ld",&l);
fscanf(stream,"%f",&fp);
fscanf(stream,"%c",&c);
/*Output data read:*/
printf("%s\n",s);
printf("%ld\n",l);
printf("%f\n",fp);
printf("%c\n",c);
fclose(stream);
}
}

posted on 2015-05-26 08:01  wesun  阅读(293)  评论(0编辑  收藏  举报