简体   繁体   English

如何将文件另存为字节数组在文本文件中? C ++

[英]How to save a file as Byte array in a text file? c++

I'm currently trying to use the sfml .loadfrommemory methods. 我目前正在尝试使用sfml .loadfrommemory方法。

My problem is that i don't know how to a file as a Byte array. 我的问题是我不知道如何将文件作为字节数组。 I've tried to code something but it does not read the whole file, and does not give me the true size of the file. 我尝试编写一些代码,但是它无法读取整个文件,并且无法提供文件的真实大小。 But I don't have an idea why. 但是我不知道为什么。

Here's my actual code: 这是我的实际代码:

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();

Got it working! 得到它的工作!

I've got it working by simply save the data to a vector. 我已经通过将数据保存到向量中来使其工作。

After getting all the Bytes i put it into a txt file. 得到所有字节后,我将其放入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;

} }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM