ccplusplus.com
Learn C, C++ Concepts
Wednesday, September 7, 2011
random string generator in c and c++
#include <iostream> #define FILE_ENTRY_SIZE (32 + 4 + 1) /* 32 hexadecimal digits PLUS 4 hyphens */ using namespace std; /* * generateRandomString.cpp * Generates a random string of 32 hexadecimal digits * Returns: * On Success, a 32-character null-terminated string * On failure, NULL * This code can be easily converted to C or C++ just by changing the header file and file extension */ char *createRandomString() { char *randomString; FILE *uuidFp; char *hyphen; randomString = (char*)malloc(sizeof(char) * (FILE_ENTRY_SIZE + 1)); if( ( uuidFp = fopen( "/proc/sys/kernel/random/uuid", "r" ) ) == NULL ) { return NULL; } if( ( uuidFp = fopen( "/proc/sys/kernel/random/uuid", "r" ) ) == NULL ) { return NULL; } if( fgets( randomString, sizeof(randomString), uuidFp ) == NULL ) { fclose( uuidFp ); return NULL; } /* * Remove all intermediate hyphens, if any */ for( ;; ) { hyphen = index( randomString, '-' ); if( hyphen == NULL ) { break; } memmove( hyphen, hyphen + 1, strlen( hyphen + 1 ) ); } fclose( uuidFp ); randomString[32] = '\0'; return randomString; } int main () { char * result = createRandomString (); printf ("%s\n", result); return 0; } /* * OUTPUT * [sgupta@rhel54x64 string]$ c++ generateRandomString.cpp -o generateRandomString [sgupta@rhel54x64 string]$ ./generateRandomString 51bce1c [sgupta@rhel54x64 string]$ */
No comments:
Post a Comment
Newer Post
Older Post
Home
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment