Reading a file in blocks

I've been working on a system to read data in blocks. It works well with text but when I try reading something like exe's it produces bad or not data. Is it possible to fix this problem if so how?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
void main ()
{
	string fileName("");
	char buffer[1025]; //let's say read by 1024 char block
	buffer[1024] = '\0';
	getline(cin,fileName);
	//std::fstream fin(fileName,ios::in | ios::binary);
	std::ifstream fin(fileName, ios::in | ios::binary);
	if (!fin) {
		std::cerr << "Unable to open file";        
	} else {
    while (true) {  
		fileName.append(buffer);
        fin.read(buffer, 1024);
        std::cout << buffer;
        if (fin.eof())
            break;
		}
	}
	system("pause");
}
Why are you trying to read something like an exe? And what do you consider bad or no data. You can't use cout to print an array of char, especially an array of char that can contain embedded '\0' characters and may contain fewer characters than what you requested leaving all the other elements of the array in an undefined state.

Last edited on
I am trying to make a system that can read a file in blocks.

I use this code to read entire files most of the time.
1
2
3
	ifstream fileIn;
	fileIn.open(theFileName, ios::in | ios::binary);
	string *theOutData = new string((istreambuf_iterator<char>(fileIn)), istreambuf_iterator<char>());

However it becomes a ram hog after you read anything larger than say 1gb.
So I tried using the code above to break the file into blocks sort of like this.


1234 5678 91011

rather than
1234567891011
Which would use too much ram. I am trying to use this an encryption system.
One of your problems is that your using cout on an array of characters, not a string. You will need to print the individual characters since this array may and probably does have embedded '\0'.
Ok
Topic archived. No new replies allowed.