Visual Studio 2017 で C++ 再入門!ファイル読み込み!
こんにちは。
仕事の自動化にやりがいと達成感を感じるガッくんです。
この記事の目次
関数
バイナリ
面倒なのでざっくりと言って二進法です。バイナリは二進法で出力されている電子データのことを指して使われていたりもします。
ソースコード①
〜バイナリ出力〜
Visual Studio 2017 Community で C++ のコンソールアプリケーションのプロジェクトで作成しました。その中のソースコードを丸ごと掲載します。
// FileDumper.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include
#include
#include
using namespace std;
// Drag & Drop で動くプログラムです。
// argc : 引数の数が代入されます。
// argv : 引数の配列が代入されます。1 個目はこのプログラムのパスが入っているので、argc は絶対 1 以上になります。
int main(int argc, char * argv[])
{
if (argc > 1) {
for (int i = 1; i < argc; i++) {
// 引数の表示
cout << "argv[" << i << "] = " << argv[i] << "\n";
////////////////////////////////////////////////////////////////////////////////
// バイナリ読み込み & ダンプ出力
////////////////////////////////////////////////////////////////////////////////
//----------------------------- バイナリファイル -----------------------------//
// 開くバイナリファイルのパス設定
string BinaryFilePath = argv[i];
//---------------------------- ダンプ出力ファイル ----------------------------//
// ダンプ出力ファイル名用変数宣言
string DumpFilePath;
// ダンプファイル用拡張子
string ext = ".dump";
// ダンプ出力ファイルはバイナリファイルに拡張子を結合したファイル名とする
DumpFilePath = BinaryFilePath + ext;
// 確認用表示
cout << DumpFilePath.c_str() << endl;
// ダンプ出力するファイルの設定
ofstream outputfile(DumpFilePath);
//--------------------------------- 共通変数 ---------------------------------//
// ルーラー
char ruler[] = "Address +0 +1 +2 +3 +4 +5 +6 +7 +8 +9 +A +B +C +D +E +F\n";
// 出力回数カウント用変数
int cnt = 0;
// 行番号出力用
long address = 0;
// 読み込むための変数宣言
unsigned char din;
//-------------------------- バイナリファイルを開く --------------------------//
// ios::in ; 読み込み専用
// ios::binary ; バイナリ形式
ifstream fin(BinaryFilePath, ios::in | ios::binary);
// バイナリファイルが開けなかったときの処理
if (!fin) {
cout << "読み込むバイナリファイルが開けません\n";
return 1;
}
// ルーラーの表示
cout << ruler;
// ルーラーの出力
outputfile << ruler;
while (!fin.eof()) {
fin.read((char *)&din, sizeof(unsigned char));
// アドレス表示
if (cnt == 0) {
printf("x ", address);
outputfile << setw(8) << setfill('0') << hex << address << " ";
}
// 何を読み込んだのかわからないけど、とりあえず標準出力
cnt += 1;
if (cnt == 16) {
printf("x\n", din); // 16進数2桁表示 + 改行
outputfile << setw(2) << setfill('0') << hex << int(din) << endl;
cnt = 0;
}
else {
printf("x ", din); // 16進数2桁表示 + スペース
outputfile << setw(2) << setfill('0') << hex << int(din) << " ";
}
// アドレス更新
address += 1;
}
cout << "\n\n";
//------------------------- バイナリファイルを閉じる -------------------------//
fin.close();
//------------------------ ダンプ出力ファイルを閉じる ------------------------//
outputfile.close();
}
}
else {
// 引数がなかった場合
cout << "バイナリファイルを Drag & Drop してください。" << "\n";
}
system("pause");
return 0;
}
以上