文件保存和读取
来源:互联网 发布:二次报销的软件 编辑:程序博客网 时间:2024/04/30 01:54
通过文件的处理,可以把内存中的数据保存到外存中,实现数据的持久化。
一、文件的保存
FILE *fp;
处理文件流程
1、打开文件
建立一个从内存到磁盘的缓冲区,把内容写到内存中。
fopen();
2、存数据
把内存中的数据映射到磁盘中,实现数据写入。
fprint()
3、关闭文件
fclose()
代码如下:
#include <stdio.h>
int main(int argc, const char * argv[])
{
FILE * fp;
//1.打开文件
fp=fopen("C:\Documents and Settings\Administrator\桌面\ok.txt", "w");
//2.写数据
fprintf(fp,"hello,wo来了");
//3.关闭文件
fclose(fp);
printf("文件写入成功\n");
return 0;
}
二、文件的读取
1.打开文件
fp=fopen("/C:\Documents and Settings\Administrator\桌面\ok.txt", "r");
2.读数据
char str[100];
fscanf(fp, "%s",str);
3.关闭文件
fclose(fp);
printf("读取文件内容:\n %s",str);
例1:在程序中录入10名学生的信息:
1、把这10名学生的成绩保存到文件
#include <stdio.h>
typedef struct _Student{
char name[10];
int age;
int number;
int score;
}Student;
int main(int argc, const char * argv[])
{ Student stus[3];
//输入学生信息
printf("请输入学生信息!\n");
for(int i=0;i<3;i++)
{ printf("请输入第%d个学生信息,格式:学号 姓名 年龄 成绩\n",i+1);
scanf("%d %s %d %d",&stus[i].number,stus[i].name,&stus[i].age,&stus[i].score);
}
//保存到文件
FILE * fp;
fp=fopen("C:\Documents and Settings\Administrator\桌面\ok.txt", "w");
for(int i=0;i<3;i++)
{
fprintf(fp,"%d %s %d %d\n",stus[i].number,stus[i].name,stus[i].age,stus[i].score);
}
fclose(fp);
return 0;
}
2、把这10名学生的成绩从文件中读取出来
#include <stdio.h>
typedef struct _Student{
char name[10];
int age;
int number;
int score;
}Student;
int main(int argc, const char * argv[])
{
Student stus[3];
//读取文件
FILE * fp;
fp=fopen("//Users//shinshen//Desktop//stu.txt", "r");
if(fp==0)
{
printf("文件打开失败!\n");
return 0;
}
int i=0;
while (!feof(fp)) {
//读取一行
fscanf(fp, "%d %s %d %d\n",&stus[i].number,stus[i].name,&stus[i].age,&stus[i].score);
i++;
}
//输出读取的内容
for(int i=0;i<3;i++)
{ printf("请输入第%d个学生信息,格式:学号%d 姓名%s 年龄%d 成绩%d\n",i+1,stus[i].number,stus[i].name,stus[i].age,stus[i].score);
}
fclose(fp);
return 0;
}
- 保存和读取文件
- 文件保存和读取
- 文件保存和读取
- 文件保存和读取
- android 保存和读取文件
- 保存和读取文件操作
- 文件的读取和保存
- 读取和保存arff文件
- Android文件保存和读取
- android 保存和读取文件
- 文件的保存和读取
- 文件的保存和读取
- 读取和保存txt文件
- FileChooser读取和保存文件
- matlab读取文件和保存文件
- Propertes文件的读取和保存
- 用JavaScript读取和保存文件
- java mysql保存和读取文件
- error C2039: 'addCameraManipulator' : is not a member of 'osgGA
- LeetCode题解: Construct Binary Tree from Preorder and Inorder Traversal
- UItableviewCell 关于Index
- apache-hadoop-1.2.1、hbase、hive、mahout、nutch、solr安装教程
- Servlet中的filter使用
- 文件保存和读取
- java 多线程 CountDownLatch用法
- udev-135 builded for rootfs sucess!
- mapreduce 比较接口
- FlashDevelop中找不到fl.transitions.Tween的问题
- openoffice在linux中的安装
- MeasureSpec
- 解决Win7加域后机器变慢的办法
- UTF-8和GBK有什么区别