2017-05-08 42 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; 

}

相关问题