Mr Aleph
Mr Aleph

Reputation: 1895

Using NSUserName() on C

I'm trying to read the username via NSUserName(). I tried the following code:

#include <stdio.h>
#include <Foundation/Foundation.h>

int main()
{
    NSString *userName = NSUserName();

    printf("username %ls\n", userName);

    return 0;
}

and compile it via:

gcc -o username -framework Foundation username.c

Several things:

1- #include <Foundation/Foundation.h> generates a LOT of errors. 2- how can I convert an NSString to char*

on 1 I am adding the -framework switch to GCC but I think the Foundation.h is not ready for C? And on 2 I tried setting char *userName = NSUserName(); but that wasn't the way to do it.

Any ideas? The code has to be C, not objective-C (as the title states)

Thanks!

Upvotes: 1

Views: 2373

Answers (3)

Chuck
Chuck

Reputation: 237110

I don't see why you'd want to do this. OS X has a way to get the same information from C, and that way is getlogin().

Foundation is an Objective-C framework and NSString is an Objective-C class. Calling it without employing Objective-C is not a simple task. Essentially, you will need to link in Foundation, include objc/objc.h for id, prototype NSUserName() yourself, use the Objective-C runtime API to get the selector for UTF8String, use the Objective-C runtime API to send the message to the string and then print the result.

All this to avoid calling getlogin().

Upvotes: 1

user149341
user149341

Reputation:

Here's a pure-C equivalent to NSUserName():

#include <pwd.h>
#include <unistd.h>

...

struct passwd *pwent = getpwuid(getuid());
printf("Username: %s\n", pwent->pw_name);

As a bonus, this will compile and work on all UNIX-based operating systems (e.g, Linux), not just Mac OS X.

Upvotes: 3

Michael Dautermann
Michael Dautermann

Reputation: 89569

change the file extension of the file holding your code from .c to .m and I bet you will have a better compiling experience.

On my machine, when I drop your code into a file named "MrAleph.m", here is what I get:

[/tmp]:;gcc -o test -framework Foundation MrAleph.m
MrAleph.m: In function ‘main’:
MrAleph.m:8: warning: format ‘%ls’ expects type ‘wchar_t *’, but argument 2 has type ‘struct NSString *’
MrAleph.m:8: warning: format ‘%ls’ expects type ‘wchar_t *’, but argument 2 has type ‘struct NSString *’

And to fix those warnings, just change one line of code to:

printf("username %s\n", [userName UTF8String]);

Upvotes: 0

Related Questions