3

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?

Flone
  • 187
  • 1
  • 3
  • 11

1 Answers1

9

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();
skeller
  • 1,151
  • 6
  • 6
  • 2
    Why do you need to wrap the iterators in parenthesis? My code does not compile when they are not included but I am not sure why. – Jacob Schneider Mar 15 '21 at 19:03
  • 2
    @JacobSchneider a similar question was asked in the comments of https://stackoverflow.com/questions/2912520/read-file-contents-into-a-string-in-c. In that case, the response was https://en.wikipedia.org/wiki/Most_vexing_parse. – paretech Jan 17 '22 at 22:23