【问题标题】:ofstream creating file before asking for its contents [duplicate]ofstream 在询问其内容之前创建文件[重复]
【发布时间】:2017-07-23 21:57:31
【问题描述】:

我正在处理的项目的一部分将有关 3D 打印机的信息保存到文本文件中。更具体地说,它应该:

  • 检查文件是否已经存在
  • 如果确实存在,请继续
  • 如果不存在,请用户输入所需数据

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

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

    }
}

【问题讨论】:

    标签: c++ ifstream ofstream


    【解决方案1】:

    是的,正如你观察到的那样

    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 我在那里看到:

    • 创建一个小帮助函数来检查文件是否存在

      bool fileExists(const char *fileName) {
          ifstream infile(fileName);
          return infile.good();
      }
      
    • 用它来判断配置文件是否存在

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

    【讨论】:

    • 谢谢,为重复道歉
    • @CadeCyphers 无需道歉。重复的问答本质上并不是坏事,只要显示的研究非常少,或者给出了一个不好的例子。如果有重复的有效问题,这些将建立一个更好的网络,用于在 Stack Overflow 上研究答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-27
    • 1970-01-01
    相关资源
    最近更新 更多