0

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
    if(!indata) 
	{ 
		// file couldn't be opened
		cerr << "Error: file could not be opened" << endl;
        exit(1);
    }

	// 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
    }

	indata.close();
    cout << "End-of-file reached.." << endl;
    return 0;
}
3
Contributors
2
Replies
3
Views
8 Years
Discussion Span
Last Post by Lerner
0

You might use std::string ...

string data;
string line;

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

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))
{
   if(!data)
   {
      lenInput = strlen(input);
      data = new char(lenInput +1);
      strcpy(data, lenInput);
   }
   else
   {
      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.