#include<iostream>
#include<fstream>
#include<string.h>
#include<stdlib.h> // for system pause ...
usingnamespace std;
int main(){
int datalen;
ifstream ifdata("data.txt");
ifdata.seekg(0, ios::end);
datalen = ifdata.tellg();
ifdata.seekg(0, ios::beg);
char data[datalen], databuff[datalen];
// code
ifdata.read(data, datalen); // first time
cout << data << endl << endl; // works
ifdata.read(databuff, datalen); // second time
cout << databuff << endl; // it does not
system("pause"); //yes, yes i know all about system pause please don't argue about that...
return (0);
}
so here's the output:
Hello World!
I'm a file.
sfB
Press any key to continue . . .
and here's the expected result
Hello World!
I'm a file.
Hello World!
I'm a file.
Press any key to continue . . .
can somebody tell me why it doesn't work and possibly how to make it work ?
PS: i know, it'll be easier to use strcpy(databuff, data) but my question is not: solve my problem ! , but, tell my why it doesn't work ?
Well, your code is explicitly designed to read all of the data into the array. Therefore the read pointer will be positioned at the end of the file after the first read.
If you wish to read the data a second time, then the ifdata.seekg(0, ios::beg); will reset the read pointer. But you knew that since you wrote the code?
#include<iostream>
#include<fstream>
#include<string.h>
#include<stdlib.h> // for system pause ...
usingnamespace std;
int main(){
int datalen;
ifstream ifdata("data.txt");
ifdata.seekg(0, ios::end);
datalen = ifdata.tellg();
ifdata.seekg(0, ios::beg);
char data[datalen], databuff[datalen];
// code
ifdata.read(data, datalen); // first time
cout << data << endl << endl; // works
ifdata.seekg(0, ios::beg); // here the missing line, that does not change much
ifdata.read(databuff, datalen); // second time
cout << databuff << endl; // it does not
system("pause"); //yes, yes i know all about system pause please don't argue about that...
return (0);
}
I overlooked that there might be an "end of file" after the first time. Therefore use clear() to reset the stream status.
Your code wouldn't compile for me. I used new [] and delete [] instead.