Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.4k views
in Technique[技术] by (71.8m points)

macos - mkdir fails with tilde on OS X in C?

I'm porting a C library to OSX which haven't given me much of a headache until now. In the next function:

int createDirectory( char *directory ){

    int error;

    error = mkdir(directory, S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);

    if( error < 0 ){

        if( errno != EEXIST ){       

            return errno;                           
        }            
    }

    return error;        
}

No matter what directory is, mkdir() always fails with EPERM (Operation not permitted). I'm not sure if the xcode executable is sandboxed or if I'm missing something, but every path I pass to the function fails.

I've tried to mkdir from the terminal and the folders are created without a problem, so I'm not sure where the problem is. This function works fine in Linux and Solaris.

Example paths:

"~/Library/Application\ Support/myApp"
"~/Desktop/myApp"

The first one is an actual example of a directory the library should create.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

OSX does not expand the '~' character as bash does (although it uses bash).

Given this program, running in /tmp:

#include <stdlib.h>
#include <sys/stat.h>
#include <stdio.h>

int main(void)
{
    char *given = "~/Library";
    char result[1024];
    char *s;
    mkdir("~", 0755);
    mkdir("~/Library", 0755);
    if ((s = realpath(given, result)) != 0) {
        printf ("%s
", s);
    } else {
        perror("realpath");
    }
    return 0;
}

I get this result on OSX:

/private/tmp/~/Library

I get this result on Linux (Debian) as well as with Solaris 10:

/tmp/~/Library

As noted in Why doesn't the tilde (~) expand inside double quotes?, this was originally a csh shell feature which bash incorporated long ago (citing a page from 1994). It is not implemented in any of the given systems' runtime libraries.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...