Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I read bytes from file? C++

Tags:

c++

file

On my desktop I have .txt file. I need to read all bytes from memory to array.

I tried to read text from file to string and then using memcpy() read bytes from string but I think this is not correct.

Tnx.

ifstream File("C:\\Users\\Flone\\Desktop\\ass.txt");
string file_text;
//start to read TEXT file (look end below):
char word_buffer[30];
for (int i = 0; i < 30; i++)
{
    word_buffer[i] = NULL;
}
while (File.eof() == false)
{
    File >> word_buffer;
    for (int i = 0; i < 30; i++)
    {
        if (word_buffer[i] != NULL)
        {
            file_text += word_buffer[i];
        }
    }
    if (File.eof()==false) file_text += " ";
    for (int i = 0; i < 30; i++)
    {
        word_buffer[i] = NULL;
    }
}
File.close();
//end read TEXT file.
cout << file_text << endl;

It works but I'm reading bytes from my string and not file or is it the same?

like image 660
Flone Avatar asked Nov 29 '25 11:11

Flone


1 Answers

mini example using vector

#include <fstream>
#include <iterator>
#include <vector>

this reads bytes from file into vector

    std::ifstream input("d:\\testinput.txt", std::ios::binary);

    std::vector<char> bytes(
         (std::istreambuf_iterator<char>(input)),
         (std::istreambuf_iterator<char>()));

    input.close();
like image 190
skeller Avatar answered Dec 02 '25 00:12

skeller



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!