簡體   English   中英

在 C++ 中讀取和顯示所有文件字節

[英]Read and display all file bytes in C++

我正在嘗試顯示 .DAT 文件中的所有字節。 我對編程完全陌生,我設法找到了如何正確顯示文件大小但我得到的每個輸出字節都是 0,即使在 HxD 中字節不全為零。

我得到的:

size is: 11
0000000000000000000000

我應該得到什么:

size is: 11
48656C6C6F20776F726C64

代碼:

#include <iostream>
#include <fstream>
#include <vector>
#include <fstream>
#include <iterator>
#include <iomanip>
using namespace std;

int main () {
  //open file and get size
  streampos begin,end;
  ifstream myfile ("TRPTRANS.DAT", ios::binary);
  begin = myfile.tellg();
  myfile.seekg (0, ios::end);
  end = myfile.tellg();
  int n;
  n=(end-begin);
  cout << "size is: " << n<<endl;

  //read file
  vector<char> randomBytes(n);
  myfile.read(&randomBytes[0], n);

  //display bytes
  for (auto& el : randomBytes)
  cout << setfill('0') << setw(2) << hex << (0xff & (unsigned int)el);
  cout << '\n';

  return 0;
}

有人可以幫我解決這個問題並正確顯示字節,謝謝

首先,你尋找到文件的末尾:

  myfile.seekg (0, ios::end);

但是你不會回到開頭,所以read調用試圖從文件的末尾讀取,但失敗了。

嘗試在read調用之前添加它:

  myfile.seekg (0, ios::beg);

之后還要檢查錯誤狀態:

  if (!myfile) {
    cerr << "could only read " << myfile.gcount() << " bytes\n";
  }

這是一個簡單的代碼,它避免查看文件大小,使用迭代器將字節讀入字符向量。

#include <iostream>
#include <fstream>
#include <iomanip>
#include <iterator>
#include <vector>

using namespace std;
int main()
{  
    ifstream input("TRPTRANS.DAT", ios::binary);
    //read bytes into vector
    vector<char> bytes(
    (istreambuf_iterator<char>(input)),
    (istreambuf_iterator<char>()));

    input.close();

    //print bytes as hex
    for (vector<char>::const_iterator i = bytes.begin(); i != bytes.end(); ++i)
        cout << setfill('0') << setw(2) << hex << (0xff & (unsigned int) *i) << endl;

    return 0;
}

如果您使用的是 C++11 標准(或更高版本),那么您可以使用 auto 關鍵字來提高可讀性:

for (auto i = bytes.begin(); i != bytes.end(); ++i)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM