如何在QBASIC中检测指定目录是否存在?并实现目录切换或创建逻辑
Checking & Creating a Directory in QBASIC
No problem at all - your request is clear, and here's how to implement that logic in QBASIC. Since QBASIC doesn't have a native function to check if a directory exists, we'll use error handling to detect missing paths and act accordingly.
Here's a complete code snippet that does exactly what you want:
ON ERROR GOTO DirErrorHandler ' Turn on error trapping ' First, try to switch to the target directory CHDIR "c:\user\basic\blablabla\" ' If we get here, the directory exists - carry on with your code PRINT "Navigated to existing directory successfully." GOTO EndOfProcess ' Skip the error handling block DirErrorHandler: ' Check if the error is "Path not found" (QBASIC error code 76) IF ERR = 76 THEN PRINT "Directory doesn't exist - creating it..." MKDIR "c:\user\basic\blablabla\" ' Create the directory CHDIR "c:\user\basic\blablabla\" ' Now switch to the new directory PRINT "Directory created and navigated to successfully." ELSE ' Catch any other unexpected errors PRINT "Oops, unexpected error: "; ERR; " - "; ERROR$ END IF EndOfProcess: ON ERROR GOTO 0 ' Turn off error trapping (good practice)
A quick breakdown of how this works:
- Error trapping setup:
ON ERROR GOTO DirErrorHandlertells QBASIC to jump to our error handling section if any command fails. - Initial CHDIR attempt: We first try to change to the target directory. If this works, the directory exists, and we skip the error handler.
- Handling missing directories: If the
CHDIRfails with error code 76 (path not found), we create the directory withMKDIRand then switch to it. - Cleanup:
ON ERROR GOTO 0disables error trapping so it doesn't interfere with other parts of your program later.
Important note:
Make sure the parent directories (c:\user\basic\) already exist! QBASIC's MKDIR can only create one directory level at a time. If you need to create nested parent directories too, you'll need to add extra logic to check and create each level individually.
内容的提问来源于stack exchange,提问作者manny-
相关产品推荐
相关产品推荐

