fprintf/fscanf函数使用举例

时间:2022-07-15 08:41:30

#include <stdio.h>

#include <stdlib.h>

 

int main()

{

       FILE *fp;

       int i,ss[4],new[4];

 

       for(i=0;i<4;i++)

       {

              scanf("%d",&ss[i]);

       }

 

       if((fp=fopen("int.txt","w+")) == NULL)

       {

              perror("int.txt--w+");

              exit(0);

       }

 

       printf("start diesplay old data!/n");

       for(i=0;i<4;i++)

       {

              printf("%d:%-10d/n",i+1,ss[i]);

             

              fprintf(fp,"ding %d,", ss[i]);//输出数据时以逗号为数据之间的分隔符

       }

       fclose(fp);

 

       printf("Now diseplay read date!/n");

 

       if((fp=fopen("int.txt","r"))==NULL)

       {

              perror("int.txt--r");

              exit(0);

       }

 

       for(i=0;i<4;i++)

       {

        //输入数据时以逗号为数据之间的分隔符,这样做到前后一致读取数据不会错

              fscanf(fp,"%d,",&new[i]);

                    

              printf("%d:%-10d/n",i+1,new[i]);

       }

 

       fclose(fp);

 

       return 0;

}

 

//分隔符也可采用/n,即回车符,那么程序中二句相应改为:

//fprintf(fp,"%d/n",ss[i]);

//fscanf(fp,"%d/n",&new[i]);