I want to read each line of text file and store each line into a giant buffer so I can look at all the contents. How would I do this?

int _tmain(int argc, _TCHAR* argv[])
	ifstream indata; // indata is like cin
    indata.open("example.txt"); // opens the file
		// file couldn't be opened
		cerr << "Error: file could not be opened" << endl;

	// keep reading until end-of-file
	char* buf = new char[50];
	char* initContent = new char[350];
    while (!indata.eof()) 
		indata.getline(buf, 50, '\n');
		memcpy(initContent, buf, 50);  //I know this isnt right but I just needed to try something

    cout << "End-of-file reached.." << endl;
    return 0;
8 Years
Discussion Span
Last Post by Lerner

You might use std::string ...

string data;
string line;

while (getline(indata, line)) 
    data += line + '\n';

If you're not into STL yet you can even do it the old C way in C++. Here's one untested idea how that might be done

char * data = NULL;
char * temp = NULL;
char input[256];
int lenInput;
int lenData;

while(indata.getline(input, 256))
      lenInput = strlen(input);
      data = new char(lenInput +1);
      strcpy(data, lenInput);
      lenData = strlen(data);
      temp = new char(lenData + 1);
      strcpy(temp, data);
      delete[] data;

      lenInput = strlen(input);
      data = new char(lenData + lenInput + 1);
      strcpy(data, temp);
      strcat(data, input);
      delete [] temp;
      temp = NULL;

That code snippet chould convince you of some of the benefits of STL if nothing else.

Here's another possibility you could try. I forget if it's tellg or tellp so look it up in your favorite reference.

//determine size of file
long long size = indata.tellg();

//declare buffer big enough to hold file.
data = new char(size +1);

//read file
indata.getline(data, size + 1, EOF);
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.