c语⾔output函数的⽤法,fprintffscanf等函数的⽤法对⽂件的读和写是最常⽤的⽂件操作。在C语⾔中提供了多种⽂件读写的函数:
·字符读写函数 :fgetc和fputc
·字符串读写函数:fgets和fputs
·数据块读写函数:fread和fwrite
·格式化读写函数:fscanf和fprinf
随着每次数据的读取,⽂件流指针fp都作相应的移动
使⽤以上函数都要求包含头⽂件stdio.h。例⼦都来⾃msdn
1 fprintf——Print formatted data to a stream
#include #include FILE *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 FILE *stream;
void main( void )
{
long l;
float fp;
char s[81];
stream = fopen( "fscanf.out", "w+" );
if( stream == NULL )
printf( "The file fscanf.out was not opened/n" ); else
{
fprintf( stream, "", "a-string",
65000, 3.14159, 'x' );
/* Set pointer to beginning of file: */
( 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");
ch=getchar();
output的反义词while (ch!='/n')
{
fputc(ch,fp);
ch=getchar();
}
rewind(fp); //Repositions the file pointer to the beginning of a file
ch=fgetc(fp);
while(ch!=EOF)
{
putchar(ch);
ch=fgetc(fp);
}
printf("/n"); fclose(fp); }

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。