- 8
- 0
- 约6.44千字
- 约 10页
- 2017-05-04 发布于湖北
- 举报
fprintf_fscan讲述
对文件的读和写是最常用的文件操作。在C语言中提供了多种文件读写的函数:
·字符读写函数 :fgetc和fputc
·字符串读写函数:fgets和fputs
·数据块读写函数:fread和fwrite
·格式化读写函数:fscanf和fprinf
随着每次数据的读取,文件流指针fp都作相应的移动
使用以上函数都要求包含头文件stdio.h。例子都来自msdn
1 fprintf——Print formatted data to a stream
#include stdio.h#include process.hFILE *stream;void main( void ){? int??? i = 10;? double fp = 1.5;? char?? s[] = this is a string;? char?? c = \n;? stream = fopen( fprintf.out, w );? fprintf( stream, %s%c, s, c );? fprintf( stream, %d\n, i );? fprintf( stream, %f\n, fp );? fclose( stream );? system( type fprintf.out );}Output
this is a string
10
1.500000
2 fscanf——Read formatted data from a stream
#include stdio.h
FILE *stream;
void 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 );
???? /* 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 );
? }
}
Output
a-string
65000
3.141590
x
3 fread——Reads data from a stream
4 fwrite——Writes data to a stream
读数据块函数调用的一般形式为:
fread(buffer,size,count,fp);
写数据块函数调用的一般形式为:
fwrite(buffer,size,count,fp);
其中:
buffer 是一个指针,在fread函数中,它表示存放输入数据的首地址。在fwrite函数中,它表示存放输出数据的首地址。
size 表示数据块的字节数。
count 表示要读??的数据块块数。
fp 表示文件指针。
5 fgets 没有看出与fread太大的区别,除了fread可以处理string外的其他不同文件的数据类型
6 fputs
7 fgetc fputs
从键盘输入一行字符,写入一个文件,再把该文件内容读出显示在屏幕上。
#i nclude
main()
{
FILE *fp;
char ch;
if((fp=fopen(d://jrzh//example//string,wt+))==NULL)
{
printf(Cannot open file strike any key exit!);
getch();
exit(1);
}
printf(input a string:\n);
原创力文档

文档评论(0)