在询问其内容之前,请创建文件

ofstream creating file before asking for its contents

本文关键字:创建 文件      更新时间:2023-10-16

项目的一部分,我正在研究的一部分我正在处理有关文本文件的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();
    }
}

是的,它是您观察到的

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
}

在我们将您的问题标记为重复之后,我想带领您为我看到的最好的解决方案提供:

  • 创建一个小的助手功能以检查文件是否存在

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

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