我想追加一個字符串到文本文件,但我變得奇怪的字符。 如果我嘗試將我的結果打印到控制檯,則輸出是常規的。 這就是我在vim中看到的輸出。如果我在gedit中查看它,我會得到奇怪的盒子。奇怪的輸出寫入文件在C
輸出文件:
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 ++;
}
}
}
如果您還顯示對該函數的調用,顯示您傳遞的參數並顯示結果將會很有幫助。 – steveha
@steveha我正在用RecursivePermute(「」,letters,&count)調用函數; //其中count = 0;和字母[] =「AAB」; – Miles