views:

154

answers:

5

Hi folks,

I'm working on a little (not so little actually) project in C (ref. this question) , and I need a little function in C that'd generate a unique and random string.

I need a small one that I can include as a utility function in a .c file. Please help me with your brains, and show me how smart this could be done!

Thanks and a virtual BIG hug for the best solution :)

EDIT: (What I just said to msw below) I actually think that I just need a random string as a key (which would look like a uuid) and I thought that'd be done with timestamps or such. (I don't want to add a bunch of files to my project just for a random key generation)

Sorry for the confusion, everyone!

EDIT2: Thank you all for your input, I'll finally use the OSSP uuid lib with SHA-1 it looks easier to implement/integrate

+2  A: 

Don't re-invent the wheel, there is probably a function that is already written on your platform of choice: http://en.wikipedia.org/wiki/Uuid#Implementations

msw
You're right msw, that's what I repeat very often. I actually think that I just need a random string as a key (which would look like a uuid) and I thought that'd be done with timestamps or such. (I don't want to add a bunch of files to my project just for a random key generation)
sandra
If you need unique **database** keys, that's a different problem with a different solution, please edit your question if this is the case. Timestamps are a bad basis for UUIDs, and [GU]UIDs are overkill for databases.
msw
msw, well lets say that I need a random string. I won't use sqlite3 as a database. I was actually wrong, what I need is a random key (that'd be unique just for me in this very app)
sandra
That's what UUIDs are designed for, see my link in this answer, and you might want to consider switching to decaf ;)
msw
;-) msw, totally!
sandra
+1  A: 

Another link for you - source of the libuuid from the ext2fs.

Nikolai N Fetissov
Thanks, Nikolai! I'm reading it now.
sandra
A: 

What about a counter?

If you are not multithreaded, just hold the actual value in a static variable. (Since you need a string you would have to do some sprintf or so to get what you need.)

If you are in fact multithreaded, when you produce your random key with sprintf glue the counter together with the thread and/or process id.

Jens Gustedt
+1  A: 

You can look at this internet draft which explains entire concept and try to implement one of the algorithm.

Praveen S
A: 

What about tmpnam ?

Alexandre C.