"您的任务是提示用户输入磁盘上路径的文件名。如果文件在指定位置不存在,则程序应退出并显示相应的错误消息" 大家好,所以这就是我遇到问题的地方,我能够让用户输入这样的文件名..
1. cout<< "enter the data file name you wish to open";
2. cin >>file;
3. indata.open(file.c_str());
4. outdata.open(file.c_str());
问题的第二部分是如果文件不存在,程序应该出错,我该怎么做呢,说我的文件名是txt.source,但是用户输入lil.pol怎么办我说它有一个错误,或者换句话说我如何使文件名成为计算机唯一接受的文件名?
答案 0 :(得分:1)
您可以尝试打开该文件,如果无法打开,请通过std::cerr
发出消息,如下所示:
std::ifstream indata(file.c_str());
if(!indata) // failed to open
{
std::cerr << "Error: could not open file: " << file << std::endl;
return 1; // error code
}
// use indata here (its open)
答案 1 :(得分:1)
编辑:
读/写数据:
void createfile()
{
ofstream file_handle("test.txt");
if (!file_handle)
return;
//add record:
file_handle << "firstname1" << endl;
file_handle << "lastname1" << endl;
file_handle << "college1" << endl;
file_handle << "1001" << endl;
//add another record:
file_handle << "firstname2" << endl;
file_handle << "lastname2" << endl;
file_handle << "college2" << endl;
file_handle << "1002" << endl;
//remember each record is 4 lines, each field is single line
//this is the file format
}
int main()
{
createfile();
ifstream fin("test.txt");
if (!fin)
{
cout << "file not found" << endl;
return 0;
}
ofstream fout("out.txt");//note, it's a different name than input file
if (!fout)
{
cout << "cannot create new file" << endl;
return 0;
}
char buffer[1000];
while (fin)
{
cout << "attempting to read record:\n";
for (int i = 0; i < 4; i++)
{
fin.getline(buffer, 1000, '\n');
if (!fin) break;
cout << buffer << endl;//write to screen
fout << buffer << endl;//write to file
if (i == 3)
{
//buffer is expected to be a number!
int number = atoi(buffer);
//multiply by random number 2, just testing
cout << number * 2 << endl;
}
}
}
return 0;
}
如果文件名错误,只需创建一个循环并请求新条目。
int main()
{
ifstream indata;
string fname;
for (;;)
{
cout << "enter fname, zero to exit\n";
cin >> fname;
if (fname == "0")
return 0;
indata.open(fname);
if (indata)
break;//file is valid and has been opened now
cout << "file not found, try again\n";
}
return 0;
}