文件的保存读取方法(笔记)
来源:互联网 发布:藤门留学收费 知乎 编辑:程序博客网 时间:2024/06/05 06:24
1. 引言:
C语言把文件看作一个字符(字节)的序列,即由一个个字符(字节)的数据顺序组成。根据数据组织形式,可分为ASCII文件和二进制文件。ASCII文件又称为文本(text)文件,它的每个字节放一个ASCII代码,代表一个字符。二进制文件是把内存中的数据按其在内存中的存储形式原样输出到磁盘上存放。
怎样保存和读取文件中的数据流呢?学会这些I/O函数即可,如下:
2. 代码示例:
该代码以图像数据的保存为例,实践了各种流数据相关函数:
#include "stdio.h"#include "opencv2/opencv.hpp"using namespace std;using namespace cv;int main(){/*【1】读取一幅图片,转化成灰度图,获取图片数据 */Mat imgBGR = imread("lena.jpg");if (imgBGR.data == NULL){printf("read img error!\n");}int width = imgBGR.cols;int height = imgBGR.rows;Mat imgGray;cvtColor(imgBGR, imgGray, CV_BGR2GRAY);uchar* pData = imgGray.data;/* 【2】fwrite保存图像信息到bat文件 */FILE* fp1 = NULL;fp1 = fopen("imgGrayInfo_fwrite.dat","wb");if (fp1 == NULL){printf("imgGrayInfo.dat not exist!\n");}// [2-1] 保存图像的宽和高fwrite(&width, sizeof(int), 1, fp1);fwrite(&height, sizeof(int), 1, fp1);// [2-2] 按行保存图像数据for (int i = 0; i < height; i ++){fwrite(pData, sizeof(char),width, fp1);fwrite("\n", sizeof(char), 1, fp1);pData += width;}fclose(fp1);/* 【3】fread读取dat文件信息 */int cols = 0, rows = 0;char tmp[2];char imgData[1024];memset(imgData, 0, sizeof(char)*1024);FILE* fp2 = NULL;fp2 = fopen("imgGrayInfo_fwrite.dat", "rb");if (NULL == fp2){printf("the dat that you want to read is not exsit!\n");}// [3-1] 读取图像的宽和高fread(&cols, sizeof(int), 1, fp2);fread(&rows, sizeof(int), 1, fp2);printf("rows:%d\t cols:%d\t", rows, cols);// [3-2] 读取图像数据for (int i = 0; i < height; i++){fwrite(imgData, sizeof(char), width, fp2);fwrite(tmp, sizeof(char), 1, fp2);}fclose(fp2);/*【4】fprintf 保存图像到txt */pData = imgGray.data;FILE* fp3 = NULL;fp3 = fopen("imgGrayInfo_fprintf.txt", "w+");if (!fp3){printf("the txt file that you want to write is not exist!\n");}// [4-1] 保存图像的宽和高fprintf(fp3,"%d%c", width,'\t');fprintf(fp3,"%d%c",height,'\n');// [4-2] 以整型方式保存图像数据for (int i = 0; i < 1; i++) //保存一行{for (int j = 0; j < width; j++){fprintf(fp3, "%d%c", *pData, '\n');pData++;}fprintf(fp3, "%c", pData,'\n');}fclose(fp3);/* 【5】fscanf读取txt数据*/int ntmp = 0;FILE* fp4 = NULL;fp4 = fopen("imgGrayInfo_fprintf.txt", "r");if (!fp4){printf("the txt file that you want to read is not exist!\n");}fscanf(fp4, "%d", &cols);fscanf(fp4, "%d", &rows);int k = 0;while (!feof(fp4)){fscanf(fp4, "%d", &ntmp);printf("%d\n", ntmp);}fclose(fp4);return 0;}
0 0
- 文件的保存读取方法(笔记)
- Android学习笔记之文件的保存与读取
- 关于文件保存到数据库及其读取的方法
- android文件保存与读取的几种方法
- 文件的读取和保存
- 文件的保存和读取
- code 文件的保存、读取
- 文件的保存和读取
- 文件的保存及读取
- OpenCV学习笔记(4)视频文件的读取与保存
- opencv学习笔记(2)视频文件的读取与保存
- Java读取文件方法 笔记
- C#笔记(4)保存数据到文件,从文件读取数据
- 文件读取的方法
- 保存、读取CFont到文件的解决方案
- Propertes文件的读取和保存
- Android----文件的保存与读取
- Android---02---文件的保存与读取
- CircleImageView-方式2
- 一条update语句,更新多个列,出现部分成功部分失败的问题
- 图像识别(2)——《OpenCV3编程入门》毛星云编著
- 用VpnService实现网络防火墙
- Ubuntu安裝MySQL
- 文件的保存读取方法(笔记)
- 火狐浏览器自动安装xpi扩展
- 面向对象_接口名作为形式参数
- 实例之HTML标签属性
- Java Serializable 对象序列化
- I,P,B帧和PTS,DTS的关系--待完善
- React-native 之Image的使用
- 实现readline,gethostname,gethostbyname
- python2.7 调用次世代验证码DLL的另类方法