0

请告诉我我在做什么是对还是错。如果它是正确的,那么为什么我会遇到分段错误?

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

char* EncodeToBase64(char*);

int main()
{
    char str[24] = {0};
    char *output = NULL;
    output = malloc(56*sizeof(char));
    scanf("%[^\n]s",str);
    output = EncodeToBase64(str);
    printf("Back %s",*output);
    return 0;
}

char* EncodeToBase64(char *str)
{
    char buff[24];
    char *output = NULL;
    output = malloc(56*sizeof(char));
    memset(buff,'0',sizeof(buff));
    printf("EncodeToBase64 Function\n");
    sprintf(buff,"echo %s | openssl enc -base64",str);
    printf("%s\n",buff);
    output = system(buff);
    printf("Back %s",*output);

    return output;
}

更正我的代码后,我又遇到了一个问题,每次我将这三个字符附加到我的字符串ô/+中......如何获得确切的字符串?

4

2 回答 2

5

system() returns an int, which is the exit status of the process, not the standard output. So assigning the return value of system() to a char * and printing that does not make any sense.

You can use popen() to start a process and read its output.

Example (using fixed sized buffers and no error checking for brevity):

char * EncodeToBase64(char *str)
{
    char buff[1024], output[1024];

    snprintf(buff, sizeof(buff), "echo %s | openssl enc -base64", str);
    FILE *fp = popen(buff, "r");
    size_t amount = fread(output, 1, sizeof(output) - 1, fp);
    output[amount] = 0; // zero terminate string
    fclose(fp);

    return strdup(output);
}

Usage:

char *b64 = EncodeToBase64("Hello world");
printf("%s", b64);
free(b64);
// Output: SGVsbG8gd29ybGQK
于 2013-08-29T09:22:22.950 回答
4
printf("Back %s",output);

打印字符串时,output是参数

free这是一个很好malloc的做法

我不认为mallocinmain()是必要的。

于 2013-08-29T09:18:27.713 回答