在询问其内容之前,请创建文件
ofstream creating file before asking for its contents
项目的一部分,我正在研究的一部分我正在处理有关文本文件的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); }
相关文章:
- 如何从Windows控制台调用.exe(C++)以在不同的目录(或任何目录)中创建文件夹?
- 避免使用 boost::进程间::消息队列创建文件
- 在C++中创建文件夹选取器对话框的最简单方法是什么?
- 如何在软件代码中使用ofstream创建文件
- 在特定 Unicode 路径中创建文件
- 两个线程一个使用流 Api,另一个线程创建文件失败并出现错误ERROR_SHARING_VIOLATION
- 即使使用 FILE_FLAG_DELETE_ON_CLOSE 属性创建文件,文件也会保留在磁盘上
- C++ 为每个结构{人}条目创建文件
- "Access is Denied" U盘上的创建文件()
- 在c++编程中的文件夹中创建文件
- 创建文件夹结构
- 在C++中创建文件夹
- 创建文件函数是否可以打开仅在WinObj实用程序中的全局目录下列出的设备的句柄?
- 使用 C++ 或 SDL 在 Android 中创建文件
- 如何检测哪些进程更改,重命名或创建文件?
- 如何在 Linux 中通过 C/C++ 以其他用户身份创建文件?
- 挂钩创建文件抛出异常:读取访问冲突
- UWP 创建文件2 ERROR_ACCESS_DENIED "NUL"
- 如何指定创建文件函数获取未缓存的结果?
- Open() 用于创建文件和打开现有文件.有人能分辨出其中的区别