3

I implemented a solution to the problem meant to be cross-platform and adherent to the C++ standard library.

bool isdir(const char *string) {
   ofstream file(string, ios::out);
   return file.fail();
}

Yet, if the file is actually writable, the program opens an empty file with string name in its working directory. How can I prevent this from happening?

Stencil
  • 1,833
  • 1
  • 17
  • 19
  • 6
    You should probably implement this using OS specific functions. You could open it as read-only, but that's not going to work either. If the path is a file which has no read permissions, your algorithm will indicate that it is a directory. – mfontanini May 21 '12 at 23:41
  • Thank you for exposing a problem I did not think of. Anyway, I am looking for a standard function, though. – Stencil May 21 '12 at 23:45
  • 1
    @Stencil There is none. The C++ standard doesn’t know about the file system. – Konrad Rudolph May 21 '12 at 23:45
  • 4
    If you want portability, boost::filesystem would probably be best. – Jesse Good May 21 '12 at 23:47
  • 2
    http://stackoverflow.com/a/328958/809387 – Griwes May 21 '12 at 23:48
  • So Boost implements platform specific functions (conditionally compiled depending on the platform)? – Stencil May 21 '12 at 23:49
  • 2
    Note that `file` will _never_ be `NULL`. You can check if the file is open with [`is_open`](http://en.cppreference.com/w/cpp/io/basic_ofstream/is_open). – Some programmer dude May 22 '12 at 05:54
  • possible duplicate of [How do i check if a file is a regular file in C++?](http://stackoverflow.com/questions/328944/how-do-i-check-if-a-file-is-a-regular-file-in-c) – Juraj Blaho May 22 '12 at 06:50
  • It is not a duplicate because I asked how to prevent ofstream constructor from creating a file in case it does not exist. – Stencil May 22 '12 at 16:15
  • @Stencil: Maybe, but first of all you asked: "Recognize file type in C++". It is in the title. – Juraj Blaho May 22 '12 at 21:46
  • Yeah, it is the title itself, which synthetizes the question. I'm grateful to you for having considered my question, and your answer is useful anyway; in fact I upvoted it, but it didn't fully satisfied what I was asking. – Stencil May 23 '12 at 09:08

1 Answers1

4

There is no standard way of detecting if a file is a directory in C++. But you can use Boost.Filesystem. It is well portable.

Edit: It seems that this question has already been answered here.

Community
  • 1
  • 1
Juraj Blaho
  • 13,301
  • 7
  • 50
  • 96