1

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

    }
}
bread bird
  • 13
  • 4

1 Answers1

0

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);
    }
    
Community
  • 1
  • 1
πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
  • thank you, apologies for the duplicate – bread bird Mar 03 '17 at 17:50
  • @CadeCyphers There's not need to apologize. Duplicate Q&A aren't inherently bad, as soon there's really low research shown, or a bad example is given. If there are valid questions duplicated, these will setup a better network for researching answers at Stack Overflow. – πάντα ῥεῖ Mar 03 '17 at 17:53