文件操作:fread()和fwrite()
2024-10-07 06:34:54
fread和fwrite函数功能
用来读写一个数据块。
一般调用形式
fread(buffer,size,count,fp);
fwrite(buffer,size,count,fp);
说明
(1)buffer:是一个指针,对fread来说,它是读入数据的存放地址。对fwrite来说,是要输出数据的地址。
(2)size:要读写的字节数;
(3)count:要进行读写多少个size字节的数据项;
(4)fp:文件型指针。
注意:1 完成次写操(fwrite())作后必须关闭流(fclose());
2 完成一次读操作(fread())后,如果没有关闭流(fclose()),则指针(FILE * fp)自动向后移动前一次读写的长度,不关闭流继续下一次读操作则接着上次的输出继续输出;
3 fprintf() : 按格式输入到流,其原型是int fprintf(FILE *stream, const char *format[, argument, ...]);其用法和printf()相同,不过不是写到控制台,而是写到流罢了。注意的是返回值为此次操作写入到文件的字节数。如int c = fprintf(fp, "%s %s %d %f", str1,str2, a, b) ;str1:10字节;str2: 10字节;a:2字节;b:8字节,c为33,因为写入时不同的数据间自动加入一个空格。
文件使用之后一定要关闭,否则将不能正确显示内容.fwrite:读入两个学生信息然后用fwrite存入文件
fread:用fread从文件中读出学生信息。
fwrite.c
#include <stdio.h>
#define SIZE 2
struct student_type
{
char name[10];
int num;
int age;
char addr[10];
}stud[SIZE];
void save()
{
FILE *fp;
int i;
if((fp=fopen("stu_list","wb"))==NULL)
{
printf("cant open the file");
exit(0);
}
for(i=0;i<SIZE;i++)
{
if(fwrite(&stud[i],sizeof(struct student_type),1,fp)!=1)
printf("file write error\n");
}
fclose(fp);
}
main()
{
int i;
for(i=0;i<SIZE;i++)
{
scanf("%s%d%d%s",&stud[i].name,&stud[i].num,&stud[i].age,&stud[i].addr);
save();
}
for(i=0;i<SIZE;i++)
{
printf("%s,%d,%d",stud[i].name,stud[i].num,stud[i].age,stud[i].addr);
}
}
fread.c
#include <stdio.h>
#define SIZE 2
struct student_type
{
char name[10];
int num;
int age;
char addr[10];
}stud[SIZE];
void read()
{
FILE *fp;
int i;
if((fp=fopen("stu_list","rb"))==NULL)
{
printf("cant open the file");
exit(0);
}
for(i=0;i<SIZE;i++)
{
if(fread(&stud[i],sizeof(struct student_type),1,fp)!=1)
printf("file write error\n");
}
fclose(fp);
}
main()
{
int i;
read();
for(i=0;i<SIZE;i++)
{
printf("%s,%d,%d,%s",stud[i].name,stud[i].num,stud[i].age,stud[i].addr);
printf("\n");
}
}
最新文章
- redis系列-主从复制
- iOS 如何适配iOS10
- Common Lisp编译程序的小技巧
- Java 参数的一些心得
- PHP 开发 APP 接口 学习笔记与总结 - JSON 结合 XML 方式封装通信接口
- mysql: 两个字段合并,字符时间转时间戳,别名字段作为where条件查询
- Redis,Memcache,mongoDB的区别
- SQLMap简单尝试
- poj 2689 (素数二次筛选)
- python:浅析python 中__name__ = &#39;__main__&#39; 的作用(转载)
- python爬虫小说代码,可用的
- Ubuntu18.04 安装 VMwareTools
- MySQL之慢查询日志分析
- LaTeX 中使两张表格并排
- Java基础知识(JAVA之IO流)
- java重点知识
- django为url写测试用例
- 使用Xstart远程图形化Linux
- Vuejs+axios+SpringMVC 1
- BigDecimalUtils BigDecimal加减乘除
热门文章
- 【VS开发】使用MFC创建并调用ActiveX控件
- springboot基于方法级别注解事务的多数据源切换问题
- poj2478(欧拉函数)
- Oracle恢复ORA-00600: 内部错误代码, 参数: [kcratr_scan_lastbwr] 问题的简单解决
- React同构起步
- 05.AutoMapper 之配置验证(Configuration Validation)
- Jade学习(一)之特性、安装
- wpf prism加载独立模块实例
- vue 条件渲染 v-if v-show
- 作为测试人员,不能不懂的adb命令和操作