using ifstream to read a file.
-
Hi! I'm creating a small program that reads from a text file, using ifstream. I'm wondering how I can tell the stream to start reading the file from the beginning? Is this possible or do I have to close the file and reopen it? This is what I'm doing: ifstream file(filename); if(!file.is_open()) { // Error message. } while(!file.eof()) { file.getline(buf, 200); // after comes more code that is not relevant here. } When I do this getline starts reading line by line. So how can I tell it to start from the beginning? Thanks!
-
Hi! I'm creating a small program that reads from a text file, using ifstream. I'm wondering how I can tell the stream to start reading the file from the beginning? Is this possible or do I have to close the file and reopen it? This is what I'm doing: ifstream file(filename); if(!file.is_open()) { // Error message. } while(!file.eof()) { file.getline(buf, 200); // after comes more code that is not relevant here. } When I do this getline starts reading line by line. So how can I tell it to start from the beginning? Thanks!
-
Hi! I'm creating a small program that reads from a text file, using ifstream. I'm wondering how I can tell the stream to start reading the file from the beginning? Is this possible or do I have to close the file and reopen it? This is what I'm doing: ifstream file(filename); if(!file.is_open()) { // Error message. } while(!file.eof()) { file.getline(buf, 200); // after comes more code that is not relevant here. } When I do this getline starts reading line by line. So how can I tell it to start from the beginning? Thanks!
You can use the
seekg
method for that. Something likeifstream input("C:\\Test.txt");
int txt = 0;
//Read a number
input >> txt;
cout << txt;// Go back to beginning
input.seekg(0, ios::beg);// Read the number again.
input >> txt;
cout << txt;Regards Senthil _____________________________ My Blog | My Articles | WinMacro