How do you read from a file (line by line)?

Hello openFrameworks people!

I have a file which I called “data.txt” which I placed in the bin/data folder. However, when I run the following code, I get an infinite loop: it keeps printing out the line “Reading:” over and over again.

I’m wondering if my syntax is correct, or if I’m not putting my data file in the correct location. Thanks for any help! :smiley:

Code:

/* Open and read from data file */
string line;
ifstream data;
data.open(“data.txt”);

while(!data.eof()){
getline(data, line);
cout << "Reading: " << line << endl;
}
data.close();

while the openframeworks objects that load files (ofVideoPlayer, ofTrueTypeFont) know about the path to the data folder, general c++ objects dont – so in that case, the trick is to use the utility function ofToDataPath(), ie:

data.open( ofToDataPath(“data.txt”).c_str() );

since ofToDataPath resturns a string, we use the .c_str() function to turn it into a char array which ifstream wants:

http://www.cplusplus.com/reference/iost-…-ream/open/

does that help?

as a side note, in 007 we’re planning to add OF based file i/o, for reading and writing binary / ascii data, which should mean less having to rely on c/c++ style file loading.

take care,
zach

Thanks, man! That fixed it. :slight_smile: