Chinaunix首页 | 论坛 | 博客
  • 博客访问: 586936
  • 博文数量: 68
  • 博客积分: 5070
  • 博客等级: 大校
  • 技术积分: 1312
  • 用 户 组: 普通用户
  • 注册时间: 2007-10-11 14:20
文章分类

全部博文(68)

文章存档

2011年(3)

2010年(30)

2009年(17)

2008年(18)

我的朋友

分类: C/C++

2008-03-14 14:54:21


【例1】从键盘输入一些字符,逐个把它们送到磁盘上,直到输入一个“#”为止。
#include < stdio.h >
main()
{FILE *fp;
 char ch,filename[10];
 scanf("%s",filename);
 if((fp=fopen(filename,"w"))==NULL)
   {printf("cannot open file\n");
   exit(0);
   }
 ch=getchar();
 while(ch!='#')
   {
    fputc(ch,fp),putchar(ch);
      ch=getchar();
   }
 fclose(fp);           
} 
    上面的程序运行情况如下
file1.c?          (输入磁盘文件名)
computer and c#?  (输入一个字符串)
computer and c

【例2】将一个磁盘文件中的信息复制到另一个磁盘文件中。
#include < stdio.h >
main()
{FILE *in,*out;
 char ch,infile[10],outfile[10];
 printf("Enter the infile name:\n");
 scanf("%s",infile);
 printf("Enter the outfile name:\n");
 scanf("%s",outfile);
 if((in=fopen(infile,"r"))==NULL)
    {printf("cannot open infile\n");
     exit(0);
    }
 if((out=fopen(outfile,"w"))==NULL)
    {printf("cannot open outfile\n");
     exit(0);
    }
 while(!feof(in))fputc(fgetc(in),out);
 fclose(in);
 fclose(out);
}
    上面的程序运行情况如下
Enter the infile name:
file1.c?(输入原有磁盘文件名)
Enter the outfile name:
file2.c?(输入新复制的磁盘文件名)                   


【例2】在磁盘文件上存有10个学生的数据。要求将第1、3、5、7、9个学生数据输入计算机。
#include < stdio.h >
struct student_type
{
 char name[10];
 int num;
 int age;
 char sex;
}stud[10]
 
main()
{int i;
 FILE *fp;
 if((fp=fopen("stud_dat","rb"))==NULL;
    {
     printf("cannot open file\n");
     exit(0);
    }
 for(i=0;i<10;i+=2)
    {
     fseek(fp,i*sizeof(struct student_type),0);
     fread(&stud[i],sizeof(struct student_type),1,fp);
     printf("%s%d%d%c\n",stud[i].name,stud[i].num,
             stud[i].age,stud[i].sex);
    }
    fclose(fp);             
}
阅读(3706) | 评论(1) | 转发(1) |
0

上一篇:VC 常见问题百问

下一篇:网站按钮问题

给主人留下些什么吧!~~

chinaunix网友2008-04-07 10:00:03

谢谢. 真不错..