-5

My question is : how can I store the content of a .txt file in a char* named m_str, in C++?

Kindly note that my file has a very defined format that I want to keep. I don't want to merge the lines together. I want what is one line 1 to stay on line 1, and what is one line 2 to stay in line 2. Because eventually I am going to serialize that char* and send it over the network, and when a node receives it, it will deserialize it and then put the content in a file and read the lines as they were in the original file.

Thank You.

pb2q
  • 56,563
  • 18
  • 143
  • 144
PeacefulSoul
  • 47
  • 1
  • 7
  • http://stackoverflow.com/questions/2975931/read-from-file-as-char-array – Ken White Jun 02 '12 at 20:59
  • possible duplicate of [Read whole ASCII file into C++ std::string](http://stackoverflow.com/questions/2602013/read-whole-ascii-file-into-c-stdstring) – Jerry Coffin Jun 02 '12 at 21:38

2 Answers2

7

You can use vector as:

std::ifstream file("file.txt");
std::istreambuf_iterator<char> begin(file), end;
std::vector<char> v(begin, end); //it reads the entire file into v

char *contentOfTheFile= &v[0]; 

The content of the file is stored in contentOfTheFile. You can use it, and modify it as well.

Nawaz
  • 341,464
  • 111
  • 648
  • 831
  • thank you nawaz for you answer, is the code snippet you posted the same as saving the file in a char* ? and would it read it the file without merging the lines together ? – PeacefulSoul Jun 02 '12 at 21:12
  • 1
    @PeacefulSoul: Why don't you experiment with it, and find out the answers to your queries yourself? Experiment is a part of learning. – Nawaz Jun 02 '12 at 21:18
0
#include <vector>
#include <fstream>
#include <stdexcept>

void foo() {
  std::ifstream stream("file.txt");
  if (!stream) throw std::runtime_error("could not open file.txt.");
  std::vector<char> str(std::istreambuf_iterator<char>(stream),
                        (std::istreambuf_iterator<char>()));
  char* m_str = str.data();
}

Should do what you need.

  • That is not going to work. `str` is not an object; it is a function declaration. Reason ; C++ vexing parse! – Nawaz Jun 02 '12 at 21:03
  • 1
    `std::vector str(std::istreambuf_iterator(stream), std::istreambuf_iterator(stream));` is a function declaration :) [Fortunately](http://ideone.com/arRRm), the compiler can catch the error, because you are using the parameter name `stream` twice. – fredoverflow Jun 02 '12 at 21:03
  • @FredOverflow I know, I just forgot. –  Jun 02 '12 at 21:05