Bytes

Given this Windows text file open in hexedit. I'm using Visual Studio.

Scenario 1:

Open using std::ifstream jconfig("jconfig.cfg");

Using ls -l it has a file size of 17 bytes.

On code snippet:

begin = jconfig.tellg();
jconfig.seekg(0, std::ios::end);
end = jconfig.tellg();
int n = end - begin; // n is 17

But when loading content into array, the array has size of 15 bytes


std::vector<unsigned char> cfg(std::istreambuf_iterator<char>{jconfig}, {});
n = cfg.size(); // n is 15

Then examining cfg buffer shows:

So two 0D are lost

And then using std::getline and checking one line, shows:

Notice instead now the NULL terminator

Scenario 2:

Open file is binary.

This snippet gives 17:

begin = jconfig.tellg();
jconfig.seekg(0, std::ios::end);
end = jconfig.tellg();
int n = end - begin; // n is 17

Then this snippet shows exactly the content:


std::vector<unsigned char> cfg(std::istreambuf_iterator<char>{jconfig}, {});
n = cfg.size(); // n is 15
buf = cfg.data();

Examining buf shows:

Content is intact

And then using std::getline examining one line of read gives:

Full code below:

int n;
std::ifstream jconfig("jconfig.cfg", std::ios::binary);
//std::ifstream jconfig("jconfig.cfg");

std::streampos begin, end;

if (jconfig.is_open()) {
    std::string line;
    std::cout << "go"; 

    begin = jconfig.tellg();
    jconfig.seekg(0, std::ios::end);
    end = jconfig.tellg();
    n = end - begin;
    const char* buf;
    unsigned char* buffer;

    jconfig.seekg(0, std::ios::beg);

    std::vector<unsigned char> cfg(std::istreambuf_iterator<char>{jconfig}, {});
    n = cfg.size();
    buffer = cfg.data();

    jconfig.seekg(0, std::ios::beg);

    while (std::getline(jconfig, line)) {
        std::cout << line; 
        buf = line.c_str();
    }
}

Here is another Unix file, contents in hexedit. Doing ls -l shows it has 47 bytes.

begin = jconfig.tellg();
jconfig.seekg(0, std::ios::end);
end = jconfig.tellg();
n = end - begin; // 47
const char* buf;
unsigned char* buffer;

... all read seems 47 fine. Be careful with notepad?

Last updated

Was this helpful?