//从键盘输入10个学生的有关数据,然后把它们转存到磁盘文件上去
/*#include <stdio.h>
#define SIZE 10
struct Student_type
{
char name[10];
int num;
int age;
char addr[15];
}stud[SIZE]; //定义全局结构体数组stud,包含10个学生数据
void save()
{
FILE *fp;
int i;
if((fp = fopen("stu.dat","wb")) == NULL)
{
printf("cannot open file\n");
return ;
}
for(i = 0; i < SIZE; i++)
if(fwrite(&stud[i],sizeof(struct Student_type),1,fp) != 1)
printf("file write error\n");
fclose(fp);
}
int main()
{
int i;
printf("Please enter data of students:\n");
for(i = 0; i < SIZE; i++)
scanf("%s%d%d%s",stud[i].name,&stud[i].num,&stud[i].age,stud[i].addr);
save();
return 0;
}
/*#include <stdio.h>
#include <stdlib.h>
#define SIZE 10
struct Student_type
{
char name[10];
int num;
int age;
char addr[15];
}stud[SIZE];
int main()
{
int i;
FILE *fp;
if((fp = fopen("stu.dat","rb")) == NULL)
{
printf("cannot open file\n");
exit(0);
}
for(i = 0; i < SIZE; i++)
{
fread(&stud[i],sizeof(struct Student_type),1,fp);
printf("%-10s %4d %4d %-15s\n",stud[i].name,stud[i].num,stud[i].age,stud[i].addr);
}
fclose(fp);
return 0;
}*/
//有一个磁盘文件,内有一些信息,要求第一次将它的内容显示在屏幕上,第2次把它复制到另一个文件上
#include <stdio.h>
int main()
{
FILE *fp1,*fp2;
fp1 = fopen("file1.dat","r");
fp2 = fopen("file2.dat","w");
while(!feof(fp1))
putchar(getc(fp1)); //逐个读入字符并输出到屏幕
putchar(10);
rewind(fp1); //是文件位置标记返回文件头
while(!feof(fp1))
putc(getc(fp1),fp2); //从文件头重新逐个读字符,输出到file2文件
fclose(fp1);
fclose(fp2);
return 0;
}
4_14练练手
最新推荐文章于 2025-04-29 01:04:55 发布