Cross-platform method of creating a folder/directory?

前端 未结 2 1472
半阙折子戏
半阙折子戏 2021-01-19 20:01

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?

2条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-19 20:35

    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 
    
    #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)
    

提交回复
热议问题