我正在尝试将字符串附加到文本文件中,但我得到了奇怪的字符。如果我尝试将结果打印到控制台,输出是正常的。这就是我在 vim 中看到的输出。如果我在 gedit 中查看它,我会得到奇怪的框。
输出文件:
A^CA^BB^A
A^CB^BA^A
B^CA^BA^A
预期输出:
AAB
ABA
BAA
我的函数应该将没有重复的排列写出到文本文件中。
功能代码:
void RecursivePermute (char *prefix, char *rest, int *ptr)
{
char *temp = malloc(sizeof(char *));
char *new_prefix = malloc(sizeof(char *));
char *rest_left = malloc(sizeof(char *));
char *rest_right = malloc(sizeof(char *));
char *new_rest = malloc(sizeof(char *));
char rest_char;
int idx = 0;
int first_occurance = 0;
int i;
FILE *file;
strcpy(temp, rest);
if (*rest == '\0')
{
*ptr += 1;
printf("Permutation %d: %s\n", *ptr, prefix);
file = fopen("permutations.txt", "a");
fprintf(file,"%s\n",prefix);
fclose(file);
return;
}
else
{
size_t rest_size = strlen(rest);
while (*rest != '\0')
{
first_occurance = (strchr(temp, *rest) - temp - idx);
if (first_occurance == 0)
{
rest_char = *rest;
rest_left = strncpy(rest_left, rest-idx, idx);
rest_right = strncpy(rest_right, rest+1, rest_size-1);
sprintf(new_rest, "%s%s", rest_left, rest_right);
sprintf(new_prefix,"%s%s", prefix, &rest_char);
RecursivePermute( new_prefix, new_rest, ptr);
}
rest++;
idx ++;
}
}
}