简体   繁体   English

C ++文件I / O问题

[英]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. 我已经尝试了所有我能想到的一切,ofstream,ifstream,添加了ios::out所有变体。 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. eof()函数在读取之后而不是在读取之前检测文件的结尾-基本上,您几乎永远不要使用它。 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对象来明确地这样做:

ifstream city( "city.txt" );

No need to mess around with ios flags. 无需弄乱ios标志。 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. 首先,如果不确定文件确实存在-将citylatlon为一些合理的默认值。

Second, you can use directly is_open member of fstream : 其次,您可以直接使用fstream is_open成员:

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. 使用ifstream.fail()检查文件是否正确打开。 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). 如果出现问题(文件不存在,或者您没有读取或读取其他信息的权限),则返回true。 So when failed you can create one with an ofstream.open(). 因此,如果失败,您可以使用ofstream.open()创建一个。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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