G++无法将.bin文件识别为输入文件的问题求助
问题解决:编译mipssim时的文件格式错误及代码优化
1. 编译错误的根本原因
你执行的编译命令g++ ./mipssim.cpp o1.bin o1.txt完全错误——g是用来编译源代码生成可执行文件的工具,你把程序运行时需要的输入输出文件(o1.bin、o1.txt)当成编译参数传给g,导致编译器把这些二进制/文本文件当成目标文件尝试链接,自然会报“文件格式无法识别”的错误。
正确的流程应该是:
- 先通过Makefile编译生成可执行文件:
make mipssim - 编译完成后,再运行生成的
mipssim可执行文件,此时才传入输入输出文件参数:./mipssim o1.bin o1.txt
2. 代码中的两处问题
(1)未定义的uint类型
代码里的uint byte = 0;会导致编译错误,因为uint不是标准C++类型,你需要使用标准的32位无符号整数类型uint32_t,同时包含<cstdint>头文件。
(2)未将内容写入输出文件
当前代码把读取到的内容输出到cout(控制台),而不是你打开的out输出流,所以最终不会生成目标output.txt文件,需要把cout << byte << endl;改成out << byte << endl;。
修正后的完整代码
#include <iostream> #include <fstream> #include <stdexcept> #include <cstdint> // 引入uint32_t的定义 using namespace std; int main(int argc, char* argv[]) { // 检查命令行参数数量是否正确 if (argc != 3) { cerr << "Usage: " << argv[0] << " input.bin output.txt\n"; return 1; } // 打开输入输出流并检查是否成功打开 ifstream in; in.open(argv[1], ios::binary); if (!in.is_open()) { cerr << "Error opening input file: " << argv[1] << endl; return 1; } ofstream out; out.open(argv[2]); if (!out.is_open()) { cerr << "Error opening output file: " << argv[2] << endl; return 1; } uint32_t data = 0; // 使用标准uint32_t类型 while (in.read(reinterpret_cast<char*>(&data), sizeof(data))) { // 用sizeof(data)代替硬编码的4,增强代码可维护性 out << data << endl; // 写入到输出文件而非控制台 } // 关闭流(程序结束时会自动关闭,显式关闭更规范) in.close(); out.close(); return 0; }
额外建议
- 可以在Makefile中添加编译选项,开启警告并指定C++标准:
CXXFLAGS = -Wall -Wextra -std=c++11 # g++默认识别CXXFLAGS变量 all: mipssim converter mipssim: mipssim.cpp g++ $(CXXFLAGS) mipssim.cpp -o mipssim converter: converter.cpp g++ $(CXXFLAGS) converter.cpp -o converter
内容的提问来源于stack exchange,提问作者Phoenix
相关产品推荐
相关产品推荐

