文件的保存讀取方法(筆記)

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;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章