非软盘环境下创建目录的代码逻辑错误求助
问题排查与修正
你的核心问题是逻辑运算符使用错误,所有判断条件都误用了||(逻辑或),导致从A/B盘运行时条件始终为真,进而执行目录创建逻辑。
错误原因分析
- 当程序从A盘运行时,
drive[0]为'A':- 第一个判断
toupper(drive[0]) != 'A' || toupper(drive[0]) != 'B'中,toupper(drive[0]) != 'B'为真,整个||表达式结果为真,进入创建分支。 - 用
stricmp的版本同理:stricmp(drive, "A:") !=0为假,但stricmp(drive, "B:") !=0为真,||表达式结果仍为真,触发创建。
- 第一个判断
- 第一个判断还有语法错误:
toupper( drive[0] != 'B' )括号位置错误,正确写法是toupper(drive[0]) != 'B'。 - 额外注意:C语言本身不支持
try/catch,如果用C编译器编译,这部分会报错,应改为检查_mkdir的返回值做错误处理。
正确代码实现
以下是修正后的完整代码,包含正确的逻辑判断和适配C语言的错误处理:
#include <stdio.h> #include <string.h> #include <ctype.h> #include <direct.h> #include <errno.h> // 示例FolderExist实现(若你已有实现可替换) int FolderExist(const char *path) { // 使用_access检查目录是否存在,0表示存在,-1表示不存在 return (_access(path, 0) == 0); } int main(int argc, char *argv[]) { char drive[_MAX_DRIVE]; char dir[_MAX_DIR]; char filen[_MAX_FNAME]; char ext[_MAX_EXT]; char SourcePath[_MAX_PATH]; char *ProgramPath = argv[0]; _splitpath(ProgramPath, drive, dir, filen, ext); strcpy(SourcePath, drive); strcat(SourcePath, dir); strcat(SourcePath, "SYSBAK"); // 正确逻辑:既不是A盘也不是B盘时才执行创建 if (toupper(drive[0]) != 'A' && toupper(drive[0]) != 'B') { if (!FolderExist(SourcePath)) { // 检查_mkdir返回值,0表示成功,-1表示失败 if (_mkdir(SourcePath) == -1) { // 可选:打印错误信息用于调试 // printf("Failed to create directory: %s\n", strerror(errno)); } } } return 0; }
其他可选判断方式
若偏好使用stricmp,正确的逻辑写法有两种(效果等价):
// 方式1:直接判断既不是A:也不是B: if (stricmp(drive, "A:") != 0 && stricmp(drive, "B:") != 0) { // 创建目录逻辑 } // 方式2:取反"是A:或B:"的判断 if (!(stricmp(drive, "A:") == 0 || stricmp(drive, "B:") == 0)) { // 创建目录逻辑 }
内容的提问来源于stack exchange,提问作者Charlie Dobson
相关产品推荐
相关产品推荐

