64,646
社区成员
发帖
与我相关
我的任务
分享
#include <stdio.h>
#include <string.h>
int main()
{
FILE *file = NULL;
char a[10];
char b[10];
fopen_s(&file, "11.txt", "w+");
fprintf_s(file, "%s %s", "aaaaa", "bbb");
fseek(file, 0, SEEK_SET);
fscanf(file, "%s %s", a, b);
fclose(file);
return 0;
}
fscanf从一个流中执行格式化输入,fscanf遇到空格和换行时结束,注意空格时也结束。
用fscanf也可以实现楼主的类似要求。只是逗号需要变成空格// crt_fscanf_s.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>
#include <stdlib.h>
FILE *stream;
int main( void )
{
long l;
float fp;
char s[81];
char c;
errno_t err = fopen_s( &stream, "fscanf.out", "w+" );
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' );
// Set pointer to beginning of file:
fseek( stream, 0L, SEEK_SET );
// Read data back from file:
fscanf_s( stream, "%s", s, _countof(s) );
fscanf_s( stream, "%ld", &l );
fscanf_s( stream, "%f", &fp );
fscanf_s( stream, "%c", &c, 1 );
// Output data read:
printf( "%s\n", s );
printf( "%ld\n", l );
printf( "%f\n", fp );
printf( "%c\n", c );
fclose( stream );
}
}
受教育了,把fscanf和fscanf_s混为一谈了。上面是fscanf_s的各种用法,读取字符串时,需要指定长度。