fscanf和sscanf在变量取值后的动作差异

fscanf和sscanf在变量取值后的动作差异

编者:李国帅

qq:9611153 微信lgs9611153

时间:2006-9-11

背景原因:

在使用vc的时候发现了一个意想不到的小问题,拿出来分享下。想当然的事情即便是在程序的世界也是危险的。

 

问题描述及期望效果:

两个函数,sscanf:Read formatted data from a string

fscanf:read the various data back from the file.

这两个函数,使用是有差异的。

fscanf( stream, "%s", s );//读完一个自动转移到下一个读取位置。

sscanf( tokenstring, "%c", &c );//读完一个不能自动转移到下一个

仔细想想,还是由它自己的道理的,对于文件操作,会有一个指向文件读写位置的指针,但格式化字符串的读取则不然。

所需资源:

Vc,

 

fscanf的例子:


// crt_fscanf.c
/* This program writes formatted data to a file.
 * It then uses fscanf to read the various data back from the file.
*/

#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' );//先把格式化的数据写入文件流
		// Security caution!
		// Beware loading data from a file without confirming its size,
		// as it may lead to a buffer overrun situation.
		/* Set pointer to beginning of file: */
		fseek( stream, 0L, SEEK_SET );

		/* Read data back from file: *///然后取出来
		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 );
	}
}

sscanf的例子:

 


 

#include <stdio.h>

int main( void )
{
   char  tokenstring[] = "15 12 14...";//用空格分隔
   char  s[81];
   char  c;
   int   i;
   float fp;

   /* Input various data from tokenstring: */
   sscanf( tokenstring, "%80s", s ); // max 80 character string
   sscanf( tokenstring, "%c", &c );//读完一个不能自动转移到下一个
   sscanf( tokenstring, "%d", &i );
   sscanf( tokenstring, "%f", &fp );

   /* Output the data read */
   printf( "String    = %s\n", s );
   printf( "Character = %c\n", c );
   printf( "Integer:  = %d\n", i );
   printf( "Real:     = %f\n", fp );
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

微澜-

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值