Reading a file in chunks

I am using the following code to read in a file, 1024 bytes at a time. The issue I am having is the last portion of the file is not being read and written to my output file. I am guessing that is because it does not completely fill the 1024 byte size but not sure if this is correct. I am not sure how to change the loop to calculate the last size if that is the problem. Thanks in advanced for any help or suggestions.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
  	ofstream debugFile;
	// open file for appending (creates file if it does not exist)
	debugFile.open("debug.txt", ios::out | ios::app);

	// check if the file to read from exists and if so read the file in chunks
	ifstream ifile(logFilePath, std::ifstream::binary);
	if (ifile.good())
	{
		std::vector<char> buffer (1024,0); // read the first 1024 bytes
		while (ifile.read(buffer.data(), buffer.size()))
		{
			debugFile << logFilePath.c_str() << " exists!" << endl;
			std::streamsize s=ifile.gcount();

			debugFile << "Data read is: " << buffer.data() << endl;

		}
		// close file
		ifile.close();
	}
	else
	{.....
Last edited on
Hi,
Make changes to your implementation, like this :
1
2
const int BUFFER_SIZE = 1024;
std::vector<char> buffer (BUFFER_SIZE + 1, 0);


And :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
	debugFile << logFilePath.c_str() << " exists!" << endl;
			debugFile << "Data read is: ";

while(1)
{
			ifile.read(buffer.data(), BUFFER_SIZE);
			std::streamsize s = ((ifile) ? BUFFER_SIZE : ifile.gcount());

			buffer[s] = 0;
			if(!ifile) cout << "Last portion of file read successfully. " << s << " character(s) read." << endl;
			debugFile <<  buffer.data() << endl << endl;
			if(!ifile) break;
		}
ifile.close();
Does that help? :)
Thanks, that did it. Appreciate the help.

Glad to hear :)
Topic archived. No new replies allowed.