如何将文件保存为文本文件中的Byte数组? C ++

时间:2022-04-01 12:41:33

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

1 个解决方案

#1


0  

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;

}

#1


0  

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;

}