回顾大一·C语言编程14.1+14.2(1)(2)+14.3

来源:互联网 发布:吉祥网络投票公司 编辑:程序博客网 时间:2024/06/08 03:19

以下程序的功能为:将随机产生的10个整数,写入到d盘的文件data.dat


#include <stdlib.h>#include <stdio.h>#include <time.h>main ( ){int a[10],i,k;  FILE *fp;   srand( (unsigned)time( NULL ) );   for (i=0;i<10;i++)  a[i]=rand();    fp=fopen ("d:\\data.dat","wb");  if(fp==NULL){ printf("Open error \n");exit(0); }  for (k=0 ; k<10 ; k++ )          fwrite(&a[k],sizeof(int),1, fp);    fclose (fp) ;            }

程序的功能为:调用fwrite函数,将5名学生的姓名和学号写入二进制文件d:\clx\w.dat中。


#include <stdio.h>struct student         { char name[20];  int num;};main( )    {struct student tel[5]={{"Jia",8888},{"Yi",7777},{"Bin",6666},{"Ding",5555},{"Wu",4444}}; int i=0;   FILE *fp=NULL; fp=fopen("d:\\clx\\w.dat");                            if(fp==NULL)   {printf("Can't open!\n");  exit(0);   }for(i=0; i<5; i++)     fwrite(&tel[i],sizeof(struct student),1,fp);                                 fclose(fp);}

下列程序的功能为:从字符指针数组读出字符串,建立ASCII码文件string.txt


#include<stdio.h>#include<stdlib.h>main(){ FILE *fp;   int i=0;   char *str[]={"AAA","BBB","CCC","DDD"};   if((fp=fopen("C:\\string.txt","r"))==NULL)   { printf("%s不能打开!\n","string.txt");     exit(1);   }   while(i<4)   {fprintf(fp,"%s",*str[i]);        i++;   }   fclose(fp);}

调用fread函数按照数据块方式从前面填空第1题产生的二进制文件d:\clx\w.dat中读取数据,然后显示在屏幕上。


#include<stdio.h>#include<stdlib.h>int main(){FILE*fp;char tel[5];int i;if((fp=fopen("d:\\clx\\w.dat"))==NULL){printf("cannot open this file!\n");exit(0);}for(i=0;i<5;i++){fread(&tel[5],sizeof(tel),1,fp);printf("%s",tel[i]);}fclose(fp);return 0;}


原创粉丝点击