操作系统大型实验进展(10)-----fprintf

来源:互联网 发布:oracle删除表及数据 编辑:程序博客网 时间:2024/06/05 08:42

fprintf

 
  是C/C++中的一个格式化写—库函数;其作用是格式化输出到一个流/文件中;
  函数完整形式: int fprintf(FILE *stream,char *format,[argument])

功 能

  传送格式化输出到一个文件中,
  可用于打印机输出。

用 法

  #include <stdio.h>
  int fprintf( FILE *stream, const char *format, ... );
  fprintf()函数根据指定的format(格式)发送信息(参数)到由stream(流)指定的文件. fprintf()只能和printf()一样工作. fprintf()的返回值是输出的字符数,发生错误时返回一个负值.

返回值

  若成功则返回输出字符数,若输出出错则返回负值。

程序例

  /* Program to create backup of the
  AUTOEXEC.BAT file */
  #include <stdio.h>
  int main(void)
  {
  FILE *in, *out;
  if ((in = fopen("\\AUTOEXEC.BAT", "rt")) == NULL)
  {
  fprintf(stderr, "Cannot open input file.\n");
  return 1;
  }
  if ((out = fopen("\\AUTOEXEC.BAT", "wt")) == NULL)
  {
  fprintf(stderr, "Cannot open output file.\n");
  return 1;
  }
  while (!feof(in))
  fputc(fgetc(in), out);
  fclose(in);
  fclose(out);
  return 0;
  }
  举例用法:
  #include <stdio.h>
  #include <process.h>
  FILE *stream;
  int 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" );
  }
  屏幕输出:
  this is a string
  10
  1.500000
  例二
  #include <stdio.h>
  int main()
  {
  FILE *fp;
  int i=617;
  char* s = "that is a good new";
  fp = fopen("text.dat","w");
  fputs("total",fp);
  fputs(":",fp);
  fprintf(fp,"%d\n",i);
  fprintf(fp,"%s",s);
  fclose(fp);
  return 0;
  }
  输出
  total:617
  that is a good new
  格式化规定符
  %d 十进制有符号整数
  %u 十进制无符号整数
  %f 浮点数
  %s 字符串
  %c 单个字符
  %p 指针的值
  %e 指数形式的浮点数
  %x, %X 无符号以十六进制表示的整数
  %0 无符号以八进制表示的整数
  %g 自动选择合适的表示法
 
转自百度百科
原创粉丝点击