0

So I'm trying to write a little C++ program to check whether or not a directory exists on a Windows platform (I am aware that other languages are more suited for this type of use, but I want to do it in c++).

This is what I have so far (it compiles):

std::string DirectorySelector::SpecifyDirectory(void)
{
    std::cout << "Enter directory for file renaming: ";
    std::cin >> directory;

    if (ValidateDirectory(directory) == 1) { SpecifyDirectory(); }
    else { return directory; }
}

int DirectorySelector::ValidateDirectory(std::string directory)
{
    error = "Error 01: Directory not found.";

    std::ifstream fin (directory);
    if (!fin) 
    { 
        std::cerr << error << "\n\n"; 
        fin.close();
        return 1;
    }
    else
    {
        fin.close();
        return 2;
    }
    }

So obviously I'm currently asking for the user to input their desired directory as a string, not sure if this is a wise choice?

I have done a little research into whether Windows folders (directories) have an extension, but it appears not.

I assume I am missing something obvious, such as a predefined C++ keyword to use somewhere?

If any answers could be fully explained as to what is going on that would be fantastic, as I don't like to use stuff which I don't understand.

Plus any tips to do with coding standards that I may not be adhering to would obviously be greatly appreciated.

Thanks in advance.

user3001499
  • 811
  • 4
  • 16
  • 32
  • by "extension" you mean a period character. Directories can contain them. I would suggest you look at boost::filesystem – CashCow Aug 13 '14 at 16:18
  • fin will close as the function exits which is just as well given the lines that close it in your code are unreachable. If the name is a directory you cannot open it with ifstream – CashCow Aug 13 '14 at 16:20
  • thanks @CashCow , have made appropriate changes – user3001499 Aug 13 '14 at 16:21

2 Answers2

1

If you want to use DIRENT (unix method) in windows then see here, advantage is cross platform (dirent is pretty much everywhere except windows):

http://www.softagalleria.net/dirent.php

If you want to use the Windows API for this:

How to check if directory exist using C++ and winAPI

Community
  • 1
  • 1
Halsafar
  • 2,540
  • 4
  • 29
  • 52
0

For a portable (across many platforms) file-management system you could use boost::filesystem

The documentation may look a bit complex for a relative beginner but they probably give you examples that will enable you to get going on what you want, and if you get stuck you can always come back here and ask specifics.

Your existing code is incorrect in its use of ifstream which is used to open a file for read-only. You cannot use this to open a directory (to list its contents or see if it exists).

CashCow
  • 30,981
  • 5
  • 61
  • 92