2017-03-03 32 views
1

我正在处理的项目的一部分将有关3D打印机的信息保存到文本文件。更具体地讲,它应该:ofstream创建文件之前询问其内容

  • 检查该文件已经存在
  • 如果它确实存在,继续前行
  • 如果它不存在,要求用户输入所需要的数据

我的问题是,该程序似乎跳过了最后一步,而不是选择创建一个空文本文件,然后继续前进,而不询问用户的数据。下面是这似乎是导致问题的块:

int configCheck() { 

    if (std::ifstream(configName)) { 

     std::cout << "Configuration file already exists." << std::endl; 

    } 
    std::ofstream file(configName); 
    if (!file) { 

     std::cout << "Configuration file not found." << std::endl; 

     // ask for machine settings 

     std::cout << "Machine Configuration" << std::endl; 
     std::cout << "---------------------" << std::endl; 
     std::cout << "Machine Width (mm): "; 
     std::cin >> xLim; 
     std::cout << std::endl; 
     std::cout << "Machine Length (mm): "; 
     std::cin >> yLim; 
     std::cout << std::endl; 
     std::cout << "Machine Height (mm): "; 
     std::cin >> zLim; 
     std::cout << std::endl; 
     std::cout << "Nozzle Size (mm): "; 
     std::cin >> nozzleDia; 
     std::cout << std::endl; 
     std::cout << "Filament Size (mm) "; 
     std::cin >> filDia; 
     std::cout << std::endl; 

     // make and fill a configuration file 

     std::cout << "Creating configuration file..." << std::endl; 
     std::ofstream config; 
     config << xLim << std::endl; 
     config << yLim << std::endl; 
     config << zLim << std::endl; 
     config << nozzleDia << std::endl; 
     config << filDia << std::endl; 
     config.close(); 

    } 
} 

回答

0

是的,这是因为你看到

std::ofstream file(configName); // Already creates the file if possible 
if (!file) { // ofstream state is good at that point and the whole 
      // code will be skipped 
} 

我们标示为重复你的问题后,我想带领你对于best possible solution我见过有:

  • 创建一个小的辅助函数来检查文件是否EXIS如果配置文件存在

    if (!fileExists(configName)) { 
        std::ofstream file(configName); 
    } 
    
+0

谢谢你,道歉重复 –

+0

@CadeCyphers有没有必要道歉TS

bool fileExists(const char *fileName) { ifstream infile(fileName); return infile.good(); } 
  • 用它来决定。重复问答本身并不坏,只要研究结果很低,或者给出了一个不好的例子。如果有重复的有效问题,这些将为Stack Overflow上的答案建立一个更好的网络。 –