2017-05-08 88 views
0

我目前正在嘗試使用sfml .loadfrommemory方法。如何將文件保存爲文本文件中的Byte數組? C++

我的問題是,我不知道如何將文件作爲字節數組。 我試過編碼的東西,但它沒有讀取整個文件, ,並沒有給我真正的文件大小。但我不知道爲什麼。

這裏是我的實際代碼:

using namespace std; 

if (argc != 2) 
    return 1; 

string inFileName(argv[1]); 
string outFileName(inFileName + "Array.txt"); 

ifstream in(inFileName.c_str()); 

if (!in) 
    return 2; 

ofstream out(outFileName.c_str()); 

if (!out) 
    return 3; 

int c(in.get()); 

out << "static Byte const inFileName[] = { \n"; 

int i = 0; 

while (!in.eof()) 
{ 
    i++; 
    out << hex << "0x" << c << ", "; 
    c = in.get(); 

    if (i == 10) { 
     i = 0; 
     out << "\n"; 
    } 
} 

out << " };\n"; 

out << "int t_size = " << in.tellg(); 
+0

你在Windows上運行?有多少文件不被讀取?難道是'\ r'字符被吞噬? –

+0

@Martin:IIRC,在某些實現中,EOF字符(26)也對文本模式下的ifstream有影響。 –

+0

@BenVoigt - 實際上,他不是。 'c'的定義(在寫入數組的開始之前)調用'in.get()'。 –

回答

0

得到它的工作!

我已經得到它的工作,只需將數據保存到一個向量。

得到所有的字節後,我把它放入一個txt文件。

#include <iostream> 
#include <sstream> 
#include <fstream> 
#include <vector> 

int main(int argc, const char* argv[]) { 

if (argc != 2) 
    return 1; 

std::string inFileName(argv[1]); 
std::string outFileName(inFileName + "Array.txt"); 

std::ifstream ifs(inFileName, std::ios::binary); 

std::vector<int> data; 

while (ifs.good()) { 
    data.push_back(ifs.get()); 
} 
ifs.close(); 

std::ofstream ofs(outFileName, std::ios::binary); 

for (auto i : data) { 

    ofs << "0x" << i << ", "; 

} 

ofs.close(); 

return 0; 

}

相關問題