Search code examples
c++cftplibcurlftp-server

Tell if a file is a directory on an FTP server


I am writing a c++ program that interfaces with an Apache FtpServer using libcurl. I was originally using the LIST command to get the contents of a directory but it was giving me a lot of information I didn't but had to parse any ways which lead to a lot unneeded overhead (especially when I was working with hundreds of thousands of files). In addition I needed a valid time stamp and it was giving me a shorthand that didn't include the year (so on January 1 all of the files on my computer looked outdated compared to the FTP server's). My solution was to use the NLST command to get only the names, then download the timestamps of each using MDTM. This worked awesome but then I ran into the major problem of not being able to tell if a file was a directory or not.

I am thinking the easiest way to do this is using the permissions to see if the first flag is set to d. FTP doesn't appear to have this functionality. Is there an easy way to tell if a filename is a directory or file?


Solution

  • You can try to use the CWD command on the file to test if it is a directory or not. But failure may mean lack of permission, so you need to check the error code. For example:

    ftp> cd atom.xml
    550 Can't change directory to atom.xml: Not a directory
    

    Alternatively, you can use the NLST command again on the file you want to test. If it is a plain file, you will just get the filename back. Otherwise, you will get a list of contents of the directory.

    ftp> nlist atom.xml
    200 PORT command successful
    150 Connecting to port 53912
    atom.xml
    226 1 matches total
    
    ftp> mkdir foo
    257 "foo" : The directory was successfully created
    ftp> nlist foo
    200 PORT command successful
    150 Connecting to port 53928
    226 0 matches total