c++,在已有一个test.bin文件,怎么读出这个文件的内容并输出
5条回答 默认 最新
关注 以下这个不错,读入二进制文件,转成16进制 写入一个文本文件
#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; ifstream in; ofstream out; cout << "Please input the File for read and write's name: " << endl; 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; }
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报
悬赏问题
- ¥20 网站后台使用极速模式非常的卡
- ¥20 Keil uVision5创建project没反应
- ¥15 mmseqs内存报错
- ¥15 vika文档如何与obsidian同步
- ¥15 华为手机相册里面的照片能够替换成自己想要的照片吗?
- ¥15 陆空双模式无人机飞控设置
- ¥15 sentaurus lithography
- ¥100 求抖音ck号 或者提ck教程
- ¥15 关于#linux#的问题:子进程1等待子进程A、B退出后退出(语言-c语言)
- ¥20 web页面如何打开Outlook 365的全球离线通讯簿功能