进阶:文件操作,学生信息管理系统"/>
C语言进阶:文件操作,学生信息管理系统
文章目录
- 1. 重定向
- 2. 读文件和写文件
- 3. 打开文件和关闭文件
- 4. 综合大题:学生信息管理系统
- 5. 二进制读文件和二进制写文件
- 6. 文件定位
- 7. 其他文件操作函数
- 8. 系统再优化之用户登录与注册
1. 重定向
重定向文件输出:
把运行出来的内容直接保存在文件中 ./a.out > hello.txt
#include <stdio.h>int main(){printf("hallo\n");
}
重定向执行结果:
[admin@localhost cfile]$ ./hi > hi.txt
[admin@localhost cfile]$ cat hi.txt
hallo
重定向文件输入:
把文件中的内容给运行后的输入 ./a.out < hello.txt
#include <stdio.h>int main(){char name[20];scanf("%s",name);printf("hallo %s\n",name);
}
重定向执行结果:
[admin@localhost cfile]$ ./hi < hi.txt
hallo hallo
其他执行情况:
[admin@localhost cfile]$ ./hi > hi.txt
123
[admin@localhost cfile]$ cat hi.txt
hallo 123
[admin@localhost cfile]$ ./hi >> hi.txt
456
[admin@localhost cfile]$ cat hi.txt
hallo 123
hallo 456
[admin@localhost cfile]$ echo abc | ./hi
hallo abc
结构体存:
结构体输出重定向到文件中
#include <stdio.h>typedef struct Student{char name[20];int age;float score;
}Stud;int main(){Stud s1 = {"张三",23,98};printf("%s %d %f\n",s1.name,s1.age,s1.score);
}
结果为:
[admin@localhost cfile]$ ./hi1 > hi1.txt
[admin@localhost cfile]$ cat hi1.txt
张三 23 98.000000
结构体取:
结构体格式的文件内容重定向到程序输入中
#include <stdio.h>typedef struct Student{char name[20];int age;float score;
}Stud;int main(){Stud s1;scanf("%s%d%f",&s1.name,&s1.age,&s1.score);printf("%s %d %f\n",s1.name,s1.age,s1.score);
}
结果为:
[admin@localhost cfile]$ ./hi1 < hi1.txt
张三 23 98.000000
[admin@localhost cfile]$ ./hi1
李四 24 92.13
李四 24 92.129997
[admin@localhost cfile]$ ./hi1 > hi1.txt
李四 24 92.13
[admin@localhost cfile]$ cat hi1.txt
李四 24 92.129997
每次重定向输入会替换文件中的内容
2. 读文件和写文件
fscanf() 写文件
fprintf() 读文件
返回实际读取的数据个数,出错或者到结尾返回 EOF
stdin是标准读,从终端读取
stdout是标准写,从终端写
在终端写入文件后直接在终端读出
#include <stdio.h>typedef struct Student{char name[20];int age;float score;
}Stud;int main(){Stud s1;fscanf(stdin,"%s%d%f",&s1.name,&s1.age,&s1.score);fprintf(stdout,"%s %d %f\n",s1.name,s1.age,s1.score);
}
结果为:
张美丽 23 97
张美丽 23 97.000000
3. 打开文件和关闭文件
fopen() 打开文件
fclose() 关闭文件
基本框架:
FILE* fp = fopen("文件路径","打开方式");if(NULL != fp){fclose(fp); }
打开方式:
NO. | 打开方式 | 含义 |
---|---|---|
1 | r | 读(默认文本文件) |
2 | w | 写,如果这个文件不存在,就创建这个文件;如果这个文件存在,则清空内容 |
3 | a | 追加,如果这个文件不存在,就创建这个文件;如果这个文件存在,则在文件尾部追加内容 |
4 | + | 以可读可写的方式打开文件,配合r、w、a使用 |
5 | t | 文本文件 |
6 | b | 二进制文件 |
FILE是一种基于文件结构的变量类型,FILE* fp; 声明了 fp 是 FILE 型指针
读取文件中的学生信息:
#include <stdio.h>typedef struct Student{char name[20];int age;float score;
} Stud;int main(){FILE* pfile = fopen("hi1.txt","r"); //打开文件if(NULL == pfile){printf("file is not existed!\n");return 1;}int n;fscanf(pfile,"%d",&n);Stud s[n];for(int i=0;i<n;++i){fscanf(pfile,"%s%d%f",&s[i].name,&s[i].age,&s[i].score);}fclose(pfile); //关闭文件for(int i=0;i<n;++i){fprintf(stdout,"%s %d %f\n",s
更多推荐
C语言进阶:文件操作,学生信息管理系统
发布评论