fprintf fscanf等函数的用法

对文件的读和写是最常用的文件操作。在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.h>

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

ch=getchar();

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

}

  • 3
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值