当与bin一起使用时,这个代码会崩溃吗?

时间:2017-02-07 07:03:04

标签: c binary crash converter

正如标题所示,我不知道我的错误在于二进制文件。

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

char binary[360];

void printstringasbinary(char* s)
{
    // A small 9 characters buffer we use to perform the conversion
    char output[9];

    while (*s)
    {
        // Convert the first character of the string to binary using itoa.
        // Characters in c are just 8 bit integers, at least, in noawdays computers.

        itoa(*s, output, 2);

        strcat(binary, output);

        ++s;
    }

}

int main(int argc, char *argv[])
{

    int i, n;

    //printf("argc: %i\n", argc);
    if (argc != 3)
    {
        puts("Converter [Text] [hex|dec|bin]");
        return 0;
    }
    FILE *f = fopen("Output.txt", "a");
    for (i = 0; i < strlen(argv[0]); i++)
    {
        if (strcmp(argv[2], "hex") == 0)
            fprintf(f, "%X ", (unsigned int) argv[1][i]);
        else if (strcmp(argv[2], "dec") == 0)
            fprintf(f, "%i ", (unsigned int) argv[1][i]);
        else if (strcmp(argv[2], "bin") == 0)
            for (n = 0; n < strlen(argv[1]); n++)
            {
                printstringasbinary(argv[1][i]);
            }
        fprintf(f, "%s ", binary);

    }
    fclose(f);

    return 0;
}

1 个答案:

答案 0 :(得分:1)

您遍历txt的字符,而$可以使用最长为argv[1][i]的字符串长度的值。取决于i是否&#34;更长&#34;比argv[0],这可能导致seg错误。 您的意思是argv[0]而不是argv[1]吗?顺便说一句:为什么 - 正如LP所指出的那样 - 你是否会迭代printstringasbinary(argv[1][n])

printstringasbinary(argv[1][i])