C++ 文件讀寫實戰——2進制文件查看器(16進制顯示)

簡單的二進制閱讀器(或者說16進制查看器)

在學習BMP位圖的構成時,對網上的收費16進制查看器很是煩躁,notepad查看時卡到放棄人生

因爲只是爲了初步學習圖片知識,以及查看2進制文件內部構成的話,可以自己實現一個

思路

  • 使用C++的文件操作進行二進制的讀操作,這裏默認以1個字節爲單位(2位16進制)

  • 每次讀一個字節,就將其轉化位16進制,讀取的時候需要注意有符號數和無符號數的區別,我這裏用unsigned Char 來存取每一個字節的內容

  • 對於C++的文件讀寫網上很多介紹

  • 對於每一個讀取的數寫入文本文件內(.txt文件)便於查看

  • 計算文件大小 通過C++的文件指針移動即首尾文件指針差除以1024即文件大小(KB)

代碼如下

#include<iostream>
#include<fstream>
#include<string>
#include<cstdlib>

using namespace std;

char HEX[16] = { '0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F' };

void transfrom(int num, char* hexNumber)
{
	for (int i = 0; i < 8; i++)
	{
		hexNumber[i] = '0';
	}
	int index = 7;
	while (num != 0 && index >= 0)
	{
		hexNumber[index--] = HEX[num % 16];
		num = num / 16;
	}
}

string getFileName(string& filename)
{
	int index = -1;
	for (int i = filename.length() - 1; i >= 0; i--)
	{
		if (filename[i] == '\\')
		{
			index = i;
			break;
		}
	}
	return filename.substr(index + 1, filename.length());
}

int main()
{
	int num = 0;    //The Byte have been read
	string path_r;
	string path_w;
	cout << "Please input the File for read and write's name: " << endl;

	ifstream in;
	ofstream out;

	while (true)
	{
		cout << "The file path to read: ";
		getline(cin, path_r);
		in = ifstream(path_r, ios::binary);
		if (!in.is_open())
		{
			cout << "Error: File Path is Wrong" << endl;
		}
		else break;
	}
	// Get the file path to Write
	cout << "The File Path to save(.txt): ";
	getline(cin, path_w);
	out = ofstream(path_w);

	//Get the File size
	long long Beg = in.tellg();
	in.seekg(0, ios::end);
	long long End = in.tellg();
	long long fileSize = End - Beg;
	in.seekg(0, ios::beg);
	out << "\t\t" << getFileName(path_r) << "\tFile Size: " << fileSize / 1024.0 << 	"KB" << endl << endl;

	//The index of every row
	char hexNumber[9] = "00000000";

	//Print the first row's index
	unsigned char temp;
	out << "\t\t"; //Format index
	for (int i = 0; i < 16; i++) out << HEX[i] << "  ";
	out << endl;



	//Read and Write File
	while (in.read((char*)&temp, 1))
	{
		if (num % 16 == 0)
		{
			out << endl;
			transfrom(num, hexNumber);
			out << hexNumber << ":\t";
		}
		num++;
		int hex = (unsigned)temp;
		char a = HEX[hex / 16];
		char b = HEX[hex % 16];
		out << a << b << " ";
	}

	out.seekp(0,ios::beg);
	
	// Close file
	in.close();
	out.close();

	cout << "Read Successfully" << endl;
	system("pause");
	return 0;
}

運行說明

  • 不能輸入輸出文件名一致(可以自己試試ㄟ( ▔, ▔ )ㄏ)
  • 首先輸入需要讀的文件(可以直接將文件拖入黑框 系統會自動輸入絕對路徑)
  • 然後輸入用於保存結果的 TXT 文件(如果不存在則在當前目錄新建)

運行截圖

以讀取Bmp圖像爲例

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