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 );
}