Is there a way to create a folder/directory \"in code\" using C, that is cross-platform? Or will I have to use the preprocessor to state which method to use?
Is there a way to create a folder/directory "in code" using C, that is cross-platform?
No. The C language and standard library have no concept of directories at all. There are standard library functions, notably fopen()
, that consume file names, which concept subsumes paths (and hence directories), but the standard specifies:
Functions that open additional (nontemporary) files require a file name, which is a string. The rules for composing valid file names are implementation-defined.
(C2011 7.21.3/8; emphasis added)
I know that doesn't speak directly to the question, but it's difficult to prove a negative, and especially to do so concisely. I'm emphasizing the point that the language standard doesn't even know that directories exist, prior to assuring you that in particular, it has no support for creating them.
Or will I have to use the preprocessor to state which method to use?
That would be a conventional way to proceed. There are several ways in which you could implement the details.
You'll need a #define
to do this.
To keep your code looking clean, you'll want use one that will define the Linux function to translate to the equivalent Windows function when compiling for Windows.
At the top of your source file, you'll have this in a Windows specific section:
#include <windows.h>
#define mkdir(dir, mode) _mkdir(dir)
Then later on you can call the function like this:
mkdir("/tmp/mydir", 0755);
Here are some others that might be useful:
#define open(name, ...) _open(name, __VA_ARGS__)
#define read(fd, buf, count) _read(fd, buf, count)
#define close(fd) _close(fd)
#define write(fd, buf, count) _write(fd, buf, count)
#define dup2(fd1, fd2) _dup2(fd1, fd2)
#define unlink(file) _unlink(file)
#define rmdir(dir) _rmdir(dir)
#define getpid() _getpid()
#define usleep(t) Sleep((t)/1000)
#define sleep(t) Sleep((t)*1000)