四时宝库

程序员的知识宝库

C语言 技能提升 系列文章(七)格式化输入/输出


当初大家入门学习C语言的时候,面对一个黑黑的命令行界面,仅有的交互方法只有printf/scanf这两个函数作为输入输出。但是,大家知道吗?这两个函数后面还有很多兄弟姐妹。那就是C语言的格式化输入输出函数,这些函数就定义在我们熟悉的stdio.h头文件中。

我们先来简单看一下他们的函数原型吧。

int      fprintf ( FILE * stream, const char * format, ... );
int      fscanf ( FILE * stream, const char * format, ... );
int      printf(const char *, ...);
int      scanf(const char *, ...);
int      sprintf(char *, const char *, ...);
int      sscanf(const char *, const char *, int ...);
int      vfprintf(FILE *, const char *, va_list);
int      vprintf(const char *, va_list);
int      vsprintf(char *, const char *, va_list);

在不同的编译器和操作系统中,所提供的这一系列函数可能会和我在这里所列出来的不太一样。

但是,上面这些函数,我能说,是所有编译器和操作系统都会支持的。

下面,我们来简单分析一下这些函数吧。这些函数的命名规则是,以printf和scanf为基础加上一些前缀。不加前缀的默认输出到控制台。

f前缀

输入输出的对象是文件,所以我们看到了参数列表中有FILE。

s前缀

输入输出的对象是字符串,所以参数列表中有一个char *。

v前缀

可以和可变参数列表(va_list)配合使用,这样的目的是可以方便大家创建封装自己的输入输出函数。至于可变参数列表是什么,我会单独写一篇来介绍。


那么我们下面直接看一下实例吧。

/* fprintf example */
#include <stdio.h>

int main ()
{
   FILE * pFile;
   int n;
   char name [100];

   pFile = fopen ("myfile.txt","w");
   for (n=0 ; n<3 ; n++)
   {
     puts ("please, enter a name: ");
     gets (name);
     fprintf (pFile, "Name %d [%-10.10s]\n",n+1,name);
   }
   fclose (pFile);
   return 0;
}
/* fscanf example */
#include <stdio.h>

int main ()
{
  char str [80];
  float f;
  FILE * pFile;

  pFile = fopen ("myfile.txt","w+");
  fprintf (pFile, "%f %s", 3.1416, "PI");
  rewind (pFile);
  fscanf (pFile, "%f", &f);
  fscanf (pFile, "%s", str);
  fclose (pFile);
  printf ("I have read: %f and %s \n",f,str);
  return 0;
}
/* sprintf example */
#include <stdio.h>

int main ()
{
  char buffer [50];
  int n, a=5, b=3;
  n=sprintf (buffer, "%d plus %d is %d", a, b, a+b);
  printf ("[%s] is a string %d chars long\n",buffer,n);
  return 0;
}
/* sscanf example */
#include <stdio.h>

int main ()
{
  char sentence []="Rudolph is 12 years old";
  char str [20];
  int i;

  sscanf (sentence,"%s %*s %d",str,&i);
  printf ("%s -> %d\n",str,i);
  
  return 0;
}
/* vprintf example */
#include <stdio.h>
#include <stdarg.h>

void WriteFormatted ( const char * format, ... )
{
  va_list args;
  va_start (args, format);
  vprintf (format, args);
  va_end (args);
}

int main ()
{
   WriteFormatted ("Call with %d variable argument.\n",1);
   WriteFormatted ("Call with %d variable %s.\n",2,"arguments");

   return 0;
}

以上就是今天的内容,希望对大家有所帮助。

发表评论:

控制面板
您好,欢迎到访网站!
  查看权限
网站分类
最新留言
    友情链接