如何将循环的值连接到变量中以便在C中返回

问题描述 投票:1回答:1

我有一个大问题。我需要做的是创建一个返回字符串的函数(接收另一个字符串作为参数)。此函数应从输入生成加密(sha256)。这是我可怕的代码,我会解释(或者我会尝试)

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

//not sure if this is the correct way to declare a string function 
//with string input parameter, but works with a dummy return
const char* Encrypt (char* Arg1)                                                                     
{  
    //varaible to generate command 
    char command[128];
    //variable to store the result
    char result[256];
    //creating command with input parameter
    snprintf(command, sizeof command, "echo -n %s | sha256sum | cut -c1-64",Arg1);  

    //popen varaible
    FILE *fpipe;
    //valdiating popen
    if (0 == (fpipe = (FILE*)popen(command, "r")))
    {
        perror("popen() failed.");
        exit(1);
    }

    //here is my problem
    char c = 0;
    while (fread(&c, sizeof c, 1, fpipe))
    {
        //when i print te "c", it shows correctly in a line
        printf("%c", c);
        //but I want to store in "result" variable for using as return

        //this doesnt work
        snprintf(result, sizeof result, "%s", c);   

        //this neither
        char c2[4];
        strcpy(c2, &c);
        strcat(result,c2);
        snprintf(result, sizeof result, "%s",c);    
    }

    printf("%c", result);

    pclose(fpipe);
    //return result; not working
    return "not woring";
}  

希望你能帮助我

c function loops return popen
1个回答
1
投票

好的,如果这是你想要做的只是将它作为一个数组添加到字符串:

char c = 0;
resultindex = 0;
while (fread(&c, sizeof c, 1, fpipe))
{
    //when i print te "c", it shows correctly in a line
    printf("%c", c);
    //but I want to store in "result" variable for using as return

    result[resultindex] = c;
    resultindex++;
}
result[resultindex] = 0;
printf("%s", result);

我没有测试 - 它可能有错误

此外,你真的应该检查并确保resultindex永远不会超过256

© www.soinside.com 2019 - 2024. All rights reserved.