Search code examples
c++ifstreamofstream

ofstream creating file before asking for its contents


Part of a project I am working on saves information about a 3D printer to a text file. More specifically, it should:

  • Check if the file already exists
  • If it does exist, move on
  • If it doesn't exist, ask the user to input the needed data

My issue is that the program seems to skip the final step, instead choosing to create an empty text file and move on without asking the user for their data. Here is the chunk that seems to be causing problems:

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

    }
}

Solution

  • Yes, it is as you observed

    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
    }
    

    After we marked your question as duplicate, I'd like to lead you for the best possible solution I've seen there:

    • Create a small helper function to check if the file exists

      bool fileExists(const char *fileName) {
          ifstream infile(fileName);
          return infile.good();
      }
      
    • Use it to decide if the configuration file exists

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