c - 从函数中获取随机字符

标签 c random passwords

我正在通过书 rn 学习 C,我正在尝试制作一个密码生成器 j4f,但我不知道如何获得随机字符。我还希望能够说出我想要多少个字符并且它应该能够从函数返回。

最佳答案

假设使用 ASCII,类似这样的东西应该可以工作:

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

char *randpw(int len) {
    char *tmp = malloc(len + 1); // +1 so there's room for null terminator
    for (int i = 0; i < len; i++) {
         /*
             choose a character between 32 and 126, inclusive,
             and put the character into the string.
         */
         tmp[i] = (rand() % (126 - 32)) + 32; 
    }
    tmp[len] = '\0'; // include null termination on string.
    return tmp;
}

int main(void) {
    srand( time( NULL));
    char *pwd = randpw(15);
    printf("%s\n", pwd);
    free(pwd);
    return 0;
}

每个字符的范围为 32 到 126。如果您查看 ASCII 表,您会发现这些是可供选择的合理字符。

此函数将分配内存,并返回一串随机字符,无论您指定的长度如何。

关于c - 从函数中获取随机字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53657771/

相关文章:

javascript - 在javascript中从数组中获取随机项的最佳方法

MySQL - 错误 1045 - 访问被拒绝

c - DevC++ C 调用 OpenCobolIDE 模块

java - 数组元素的算术方程不起作用

c - "Vigenere": String lowercasing program is appending character for some inputs

python - 排除 random.choice() 生成的特定字符

facebook - 我可以更改测试用户的密码吗

database - 安全存储无法加密的凭据

c# - TextWriter.ReadToEnd 与 Unix wc 命令

c - 如何将函数指针分配给函数