C语言文件操作----fscanf

来源:互联网 发布:flex2找不到软件 编辑:程序博客网 时间:2024/05/16 05:30

fscanf函数的一般形式

  函数名: fscanf
  功 能: 从一个流中执行格式化输入,fscanf遇到空格和换行时结束,注意空格时也结束。这与fgets有区别,fgets遇到空格不结束。
  用 法: int fscanf(FILE *stream, char *format,[argument...]);
  int fscanf(文件指针,格式字符串,输入列表);
  for example:
  FILE *fp;
  char a[10];
  int b;
  double c;
  fscanf(fp,"%s%d%lf",a,&b,&c)
  返回值:整型,数值等于[argument...]的个数

格式字符说明

  常用基本参数对照:
  %d:读入一个十进制整数.
  %i :读入十进制,八进制,十六进制整数,与%d类似,但是在编译时通过数据前置来区分进制,如加入“0x”则是十六进制,加入“0”则为八进制。例如串“031”使用%d时会被算作31,但是使用%i时会算作25.
  %u:读入一个无符号十进制整数.
  %f %F %g %G : 用来输入实数,可以用小数形式或指数形式输入.
  %x %X: 读入十六进制整数.
  %o': 读入八进制整数.
  %s : 读入一个字符串,遇空格结束。
  %c : 读入一个字符。无法读入空值。空格可以被读入。
  附加格式说明字符表修饰符说明  
L/l 长度修饰符 输入"长"数据
  h 长度修饰符 输入"短"数据
  示例说明
  如果要求从标准输入中输入一串字符串和一个整型数,那么参数“%s%d”表示什么呢?默认情况下,在终端上(这里假设程序为控制台应用程序)输入第一个参数的值的时候敲下回车,则在第二行输入的为第二个参数值,采用这种输入方法那么格式字符的形式就无关紧要了。
  这里要特殊说明的是如果参数在同一行给出,那么格式字符的参数与终端的输入会有什么关系。举个例子:如果格式字符为“%s+%d”,那么参数的输入就应该为 string + integer。

 

 #include <stdlib.h>

 #include <stdio.h>

  int main(void)
  {
  int i;
  printf("Input an integer: ");
  /* read an integer from the
  standard input stream */
  if (fscanf(stdin, "%d", &i))
  printf("The integer read was: %d\n",i);
  else
  {
  fprintf(stderr, "Error reading an \
  integer from stdin.\n");
  exit(1);
  }
  return 0;
  }
  返回EOF如果读取到文件结尾。

 

  附:MSDN中例子
  Example
  /* FSCANF.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>
  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 );
  }
  }