views:

139

answers:

4

I am trying to open a file which normally has content, for the purpose of testing i will like to initialize the program without the files being available/existing so then the program should create empty ones, but am having issues implementing it. This is my code originally

void loadFiles() {
fstream city;
    city.open("city.txt", ios::in);
fstream latitude;
    latitude.open("lat.txt", ios::in);
fstream longitude;
    longitude.open("lon.txt", ios::in);
while(!city.eof()){
    city >> cityName;
    latitude >> lat;
    longitude >> lon;
    t.add(cityName, lat, lon);
}
city.close();
latitude.close();
longitude.close();
}

I have tried everything i can think of, ofstream, ifstream, adding ios::out all all its variations. Could anybody explain me what to do in order to fix the problem. Thanks!

+3  A: 

You have posted code for reading files, not creating empty ones - you need t expand your question in this regard. And what you have posted is not good code for reading. The eof() function detects end of file following a read, not before one - basically, you should almost never use it. Instead, you should test the success of each read:

while( (city >> cityName) && (latitude >> lat) && (longitude >> lon) {
    t.add(cityName, lat, lon);
}

Also, if you want to create an input stream, why not do so explicitly using an ifstream object:

ifstream city( "city.txt" );

No need to mess around with ios flags. You should really test if the open worked too:

if ( ! city.is_open() ) {
   throw "open failed" ;   // or whatever
}
anon
thanks a lot Neil! specially for the best-practices tips
Carlucho
+1  A: 

Use ifstream.fail() to check if file is opened properly. It returns true if something goes wrong (file does not exists or you do not have permission to read or stg else I am unaware of). So when failed you can create one with an ofstream.open().

tafa
+1  A: 

If you want to (non-destructively) create a file if there isn't one, you can open it in append mode (ios::app), which will create it if it doesn't exist, and leave it untouched if it does.

tzaman
+1  A: 

First, if you are unsure that files do exists - set city, lat and lon to some sane defaults.

Second, you can use directly is_open member of fstream:

fstream f;
f.open("f.txt", ios::in);
if (f.is_open()) {
    // attempt reading here
} else {
    f.open("f.txt", ios::out | ios::app); // create empty file
}

If reading from files fails for some reason you still have all variables set to defaults.

Marcin Gil