简体   繁体   中英

C++ File I/O problem

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!

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
}

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.

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().

如果要(无损地)创建文件(如果没有),则可以以附加模式( ios::app )打开它,如果文件不存在,它将创建该文件;如果文件不存在,则保持不变做。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM