You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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 DirErrorHandler tells 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 CHDIR fails with error code 76 (path not found), we create the directory with MKDIR and then switch to it.
  • Cleanup: ON ERROR GOTO 0 disables 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-

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 08:56:20