#include <stdio.h>
#include <stdlib.h>
FILE *stream;
int main( void )
{
long l;
float fp;
char s[81];
char c;
errno_t err;
err = fopen_s( &stream, "fscanf.out", "w+" );
// fopen的返回值是文件指针,而fopen_s的返回值是相应的错误代码,有助于排查问题
if( err )
printf_s( "The file fscanf.out was not opened\n" );
else
{
// 写入
fprintf_s( stream, "%s %ld %f%c", "a-string",
65000, 3.14159, 'x' );
// 设置文件指针指向文件头
fseek( stream, 0L, SEEK_SET );
// 读出
fscanf_s( stream, "%s", s, _countof(s) ); // 读字符串,要加上字符串长度参数
fscanf_s( stream, "%ld", &l ); // 读整数
fscanf_s( stream, "%f", &fp ); // 读浮点数
fscanf_s( stream, "%c", &c, 1 ); //读单个字符,注意要加上参数1
// Output data read:
printf( "%s\n", s );
printf( "%ld\n", l );
printf( "%f\n", fp );
printf( "%c\n", c );
// 释放文件资源,关闭文件
fclose( stream );
}
}
网友评论