C语言课程设计——文件基本操作4

/*
随机读写
通过操作文件的位置指针移动到不同的位置进行文件的读写叫随机读写

用rewind(fp)使文件的位置指针移动到文件开始的位置
无返回值
 
 
用fseek(fp,偏移, 位置指针)
偏移是long类型 
位置指针:
SEEK_SET: 文件开头	0
SEEK_CUR: 当前位置	1
SEEK_END: 文件结尾	2


用ftell(fp)得到文件位置指针当前位置相对于文件首的偏移字节数。
*/
/*
建立一个磁盘文件stu1.dat,文件中存储学生信息,然后对文件进行读访问,
第一次打屏,第二次写入stu2.dat中。
*/
#include 
#include 
#include 

typedef struct{
	char name[32];
	char num[32];
	int age;
	char address[32];
}student;
student stu[5]={
	{"name1", "num1", 10, "add1"},
	{"name2", "num2", 10, "add2"},
	{"name3", "num3", 10, "add3"},
	{"name4", "num4", 10, "add4"},
	{"name5", "num5", 10, "add5"}
};

void write()
{
	FILE *fp;
	fp=fopen("D:\\stu1.dat", "wb");
	if (fp==NULL){
		printf("error\n");
		exit(-1);
	}
	for (int i=0; i<5; i++){
		fwrite(&stu[i], sizeof(student), 1, fp);
	}
}
int main()
{
	
	write();
	
	
	FILE *fp1, *fp2;
	fp1=fopen("D:\\stu1.dat", "rb");
	if (fp1==NULL){
		printf("error\n");
		exit(-1); 
	}
	for (int i=0; i<5; i++){
		fread(&stu[i], sizeof(student), 1, fp1);
		printf("%s %s %d %s\n", stu[i].name, stu[i].num, stu[i].age, stu[i].address);
	}
	
	rewind(fp1);
	
	fp2=fopen("D:\\stu2.dat", "wb");
	if (fp2==NULL){
		printf("error\n");
		exit(-1); 
	}
	for (int i=0; i<5; i++){
		fread(&stu[i], sizeof(student), 1, fp1);
		fwrite(&stu[i], sizeof(student), 1, fp2);
	}
		
	fclose(fp1);
	fclose(fp2);
	return 0;
}
/*
在磁盘文件stu1.dat上已有的10个学生数据,从文件中读取1,3,5,7,9学生信息并打屏。
*/
#include 
#include 
#include 

typedef struct{
	char name[32];
	char num[32];
	int age;
	char address[32];
}student;
student node;
student stu[10]={
	{"name01", "num01", 10, "add1"},
	{"name02", "num02", 10, "add2"},
	{"name03", "num03", 10, "add3"},
	{"name04", "num04", 10, "add4"},
	{"name05", "num05", 10, "add5"}, 
	{"name06", "num06", 10, "add6"},
	{"name07", "num07", 10, "add7"},
	{"name08", "num08", 10, "add8"},
	{"name09", "num09", 10, "add9"},
	{"name10", "num10", 10, "add0"},
};
void write()
{
	FILE *fp;
	fp=fopen("D:\\stu1.dat", "wb");
	if (fp==NULL){
		printf("error\n");
		exit(-1);
	}
	for (int i=0; i<10; i++)
		fwrite(&stu[i], sizeof(student), 1, fp);
	fclose(fp);
}
int main()
{
	write();
	
	FILE *fp;
	fp=fopen("D:\\stu1.dat", "rb");
	if (fp==NULL){
		printf("error\n");
		exit(-1);
	}
	for (int i=0; i<10; i+=2){
		fseek(fp, (long)sizeof(student)*i, 0);//改变位置指针 
		fread(&node, sizeof(student), 1, fp);
		printf("%s	%s	%d	%s\n", node.name, node.num, node.age, node.address);
	}
	return 0;
}

你可能感兴趣的:(课程设计/实践)