【问题标题】:C++ reading an output file which should already existC ++读取应该已经存在的输出文件
【发布时间】:2016-11-16 04:58:15
【问题描述】:

如何提示用户输入输出文件名和IF not found 重试?

每次发生这种情况时,它都会创建输出文件;我不希望我只希望它读取输出文件。

do{
cout <<"Type the name of the output file which will hold the simulation             results:\n";
cin >> nameoutputfile;
fileout.open(nameoutputfile);

if (fileout.fail())
{
cout << "ERROR: File "<< nameoutputfile <<" could not be opened\n";
tries[1]++;
}
if (tries[1] == trylimit)
{
cout << "ERROR: You exceeded maximum number of tries allowed\n";
cout << "while entering the input file name";
return 2;
}
}while(fileout.fail());

这就是输出应该是什么

outputReadOnly.txt   
ERROR: File outputReadOnly.txt could not be opened    
Type the name of the output file which will hold the simulation results:  
outputReadOnly.txt  
ERROR: File outputReadOnly.txt could not be opened  
Type the name of the output file which will hold the simulation results:  
outputReadOnlyt.txt  
ERROR: You exceeded maximum number of tries allowed  
while entering the output file name 

【问题讨论】:

  • 你的文件输出对象是什么类型的?
  • 文件可以是任何东西,但必须存在
  • 我的意思是你如何初始化变量?

标签: c++ visual-studio c++11


【解决方案1】:

看起来您正在使用ofstream fileout;,默认情况下会覆盖现有文件。要实现所需的行为,您可以使用 fstream 并指定两个 in | out 标志:

fstream fileout;
do{
  // Other code skipped for simplicity
  fileout.open(nameoutputfile, ios_base::in|ios_base::out);
  // ...
}while(fileout.fail());

这是fstream.open使用的默认标志,所以你可以写:

fileout.open(nameoutputfile);

【讨论】:

  • 不明白,但我试图做的是确保文件没有被创建但应该已经存在
  • @johnsmith 是的,我明白了。将您的信息流声明为fstream fileout
  • 好的,但是如果文件不存在它会重新提示我该怎么做
  • 是否可以编写代码来复制输出
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-12-15
  • 1970-01-01
  • 1970-01-01
  • 2018-08-02
  • 2013-11-01
  • 2018-10-24
  • 2010-10-21
相关资源
最近更新 更多