free pascal里能不能判断某个目录是否存在?

2025-04-27 06:56:07
推荐回答(1个)
回答1:

可以~

DirectoryExists,FileGetAttr或FindFirst等都可以,但需要uses sysutils; 如果平台相关的,比如Windows下,还可以调用Windows API GetFileAttributes / GetFileAttributesEx,FindFirstFile;PathIsDirectory,PathFileExists(shell函数)等。

① 代码

program check_directory_existence;
uses sysutils, windows;
var
    s : String;
    info : TSearchRec;
    ret : Integer;
    wfd : WIN32_FIND_DATA;
    hnd : THandle;
begin
    readln(s);
    writeln('1. DirectoryExist()...');
    if DirectoryExists(s) then writeln('  Directory exists!')
    else writeln('  Directory does NOT exist!');

    writeln('2. FileGetAttr()...');
    if (FileGetAttr(s) and faDirectory) <> 0 then writeln('  Exist.')
    else writeln('  Not exist.');

    writeln('3. FindFirst()...');
    if (FindFirst(s, faDirectory, info) = 0) then writeln('  Yes!')
    else writeln('  NO...');

    writeln('4. GetFileAttributes ()...');
    ret := GetFileAttributes(Addr(s[1]));    
    if (ret <> -1) and ( (ret and FILE_ATTRIBUTE_DIRECTORY) <> 0) then writeln('  hahaha!')
    else writeln('  ooops...');    

    writeln('5. FindFirstFile ()...');
    hnd := FindFirstFile(Addr(s[1]), wfd);
    if (hnd <> INVALID_HANDLE_VALUE) and ((wfd.dwFileAttributes and FILE_ATTRIBUTE_DIRECTORY) <> 0) then writeln('  Cool!')
    else writeln(' Shot.');
end.

② 运行