C生成最大长度的随机字符串

C generate random string of max length

我想生成一个仅由小写 ASCII 字符组成的随机字符串(意思是小写字母、数字和其他 ASCII 字符;只是没有大写字母)。

字符串的最大长度应为 587 个字符(包括空终止符)。

我该怎么做?

谢谢

#define N 588

#include <stdlib.h>
#include <time.h>
void gen(char *dst)
{
    int i, n;  

    srand(time(NULL));               /* init seed */
    if ((dst = malloc(N)) == NULL)   /* caller will need to free this */
        return;
    for (i = 0; i < N; )
        if ((n = rand()) < 'A' && n > 'Z')
            dst[i++] = n;
    dst[N - 1] = 0;                   /* null terminate the string */
}

这样你就可以用你想要的任何字符做一个随机字符串。唯一的问题是你应该把它们放在函数中

#include <stdlib.h>

void gen_random(char *s, const int len) {
    static const char alphanum[] =
        "0123456789"
        "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
        "abcdefghijklmnopqrstuvwxyz";

    for (int i = 0; i < len; ++i) {
        s[i] = alphanum[rand() % (sizeof(alphanum) - 1)];
    }

    s[len] = 0;
}

我试过这个:

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <time.h>
#include <ctype.h>

#define BUFFER_SIZE 587 /* 587 including NULL so 0..585 and 586 is NULL */

int main(int argc, char** argv)
{   
    size_t i;
    char buffer[BUFFER_SIZE];
    int x;

    srand((unsigned int)time(NULL));
    memset(buffer, 0, sizeof(buffer));

    for (i = 0; i < BUFFER_SIZE-1; i++)
    {       
        /* Note: islower returns only a b c..x y z, isdigit 0..9 and isprint only printable characters */
        do
        {
            x = rand() % 128 + 0; /* ASCII 0 to 127 */
        }
        while (!islower(x) && !isdigit(x) && !isprint(x)); 

        buffer[i] = (char)x;
    }

    buffer[BUFFER_SIZE-1] = '[=10=]';

    printf("%s", buffer);

    getchar();

    return EXIT_SUCCESS;
}