C++ 在请求文件内容之前创建文件的流
我正在处理的项目的一部分将有关3D打印机的信息保存到文本文件中。更具体地说,它应该:C++ 在请求文件内容之前创建文件的流,c++,ifstream,ofstream,C++,Ifstream,Ofstream,我正在处理的项目的一部分将有关3D打印机的信息保存到文本文件中。更具体地说,它应该: 检查文件是否已经存在 如果确实存在,请继续 如果不存在,请要求用户输入所需的数据 我的问题是,程序似乎跳过了最后一步,而是选择创建一个空文本文件,然后继续,而不要求用户提供数据。以下是可能导致问题的区块: int configCheck() { if (std::ifstream(configName)) { std::cout << "Configuration f
- 检查文件是否已经存在
- 如果确实存在,请继续
- 如果不存在,请要求用户输入所需的数据
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();
}
}
intconfigcheck(){
if(std::ifstream(configName)){
是的,正如你所观察到的
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);
}
- 使用它来确定配置文件是否存在
bool fileExists(const char *fileName) {
ifstream infile(fileName);
return infile.good();
}
if (!fileExists(configName)) {
std::ofstream file(configName);
}
是的,正如你所观察到的
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);
}
- 使用它来确定配置文件是否存在
bool fileExists(const char *fileName) {
ifstream infile(fileName);
return infile.good();
}
if (!fileExists(configName)) {
std::ofstream file(configName);
}
谢谢你,我为这次事故道歉duplicate@CadeCyphers不需要道歉。重复的问答并非天生就不好,只要有真正低的研究显示,或给出了一个不好的例子。如果有重复的有效问题,这些将建立一个更好的网络,以便在堆栈溢出时研究答案。谢谢,为重复道歉@学员无需道歉。重复的问答并非天生就不好,只要出现了真正低水平的研究,或给出了一个不好的例子。如果有重复的有效问题,这将为在堆栈溢出时研究答案建立一个更好的网络。