Chinaunix首页 | 论坛 | 博客
  • 博客访问: 5617
  • 博文数量: 1
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 10
  • 用 户 组: 普通用户
  • 注册时间: 2016-11-17 12:58
文章分类
文章存档

2016年(1)

我的朋友
最近访客

分类: C/C++

2016-11-18 09:09:17

原文地址:C语言对文件的操作 作者:luojingqing


【例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);             
}
阅读(1039) | 评论(0) | 转发(0) |
0

上一篇:没有了

下一篇:没有了

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