使用fputc和fgetc实现文件的拷贝功能
#include <myhead.h>
int main(int argc, const char *argv[])
{
FILE *fp = fopen(argv[1], "r");
FILE *fq = fopen( argv[2],"w");
if(NULL == fq || NULL == fp)
{
perror("fopen");
return 1;
}
while(1){
char ch = fgetc(fp);
if(EOF == ch){break;}
fputc(ch, fq);
}
return 0;
}
将结构体数组的加载保存代码,把结构体数组改成链表再来一次
#include <myhead.h>
#include <string.h>
typedef struct student
{
char name[20];
int chinese;
int math;
int english;
int physics;
int chemical;
int biology;
}stu;
typedef struct student_node
{
stu student;
struct student_node *next;
int len;
}stu_node, *stu_node_p;
stu_node_p node_create()
{
stu_node_p p = (stu_node_p)malloc(sizeof(stu));
if(NULL == p)
{
printf("申请失败");
return NULL;
}
return p;
}
int main(int argc, const char *argv[])
{
stu_node_p H = (stu_node_p)malloc(sizeof(stu_node));
if(NULL == H)
{
printf("头结点创建失败");
return 0;
}
H -> len = 0;
H -> next = NULL;
stu srr[5] = {{"李",1,1,1,1,1,1},
{"王",2,2,2,2,2,2},
{"刘",3,3,3,3,3,3},
{"张",4,4,4,4,4,4},
{"胡",5,5,5,5,5,5}};
do
{
stu_node_p p = node_create();
p -> student = srr[H -> len];
p -> next = H -> next;
H -> next = p;
H -> len++;
}while(H -> len < 5);
FILE *fp = fopen(argv[1], "w");
if(NULL == fp)
{
perror("fopen");
return 1;
}
stu_node_p p = H -> next;
do
{
fprintf(fp, "%s %d %d %d %d %d %d\n",
p -> student.name,
p -> student.math,
p -> student.chinese,
p -> student.english,
p -> student.physics,
p -> student.chemical,
p -> student.biology);
p = p -> next;
}while(p != NULL);
p = H -> next;
for(int i = 0; i < H -> len; i++)
{
printf("%s %d %d %d %d %d %d\n",
p -> student.name,
p -> student.math,
p -> student.chinese,
p -> student.english,
p -> student.physics,
p -> student.chemical,
p -> student.biology);
p = p -> next;
}
fclose(fp);//调用完需要关闭,方便其他文件流调用文件
#if 1
//清空后从新读取
p = H -> next;
do
{
memset(&p -> student, 0, sizeof(p -> student));
p = p -> next;
}while(p != NULL);
FILE *fq = fopen(argv[1], "r");
if(NULL == fq)
{
perror("open");
return 1;
}
p = H -> next;
do
{
fscanf(fq, "%s %d %d %d %d %d %d\n",
p -> student.name,
&p -> student.math,
&p -> student.chinese,
&p -> student.english,
&p -> student.physics,
&p -> student.chemical,
&p -> student.biology);
p = p -> next;
}while(p != NULL);
p = H -> next;
for(int i = 0; i < H -> len; i++)
{
printf("%s %d %d %d %d %d %d\n",
p -> student.name,
p -> student.math,
p -> student.chinese,
p -> student.english,
p -> student.physics,
p -> student.chemical,
p -> student.biology);
p = p -> next;
}
#endif
fclose(fq);
return 0;
}