I am trying to append a string to a text file, but I am getting odd characters.
If I try to print out my result to the console, output is regular.
This is what i see as the output in vim. If I look at it in gedit I get strange boxes.
Output File:
A^CA^BB^A
A^CB^BA^A
B^CA^BA^A
Expected Output:
AAB
ABA
BAA
My function should write out the permutations with no duplicates into a text file.
Code For Function:
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 ++;
}
}
}
One thing is that your printf format specifier for &rest_char is wrong. &rest_char can’t be interpreted as a string because it is not null-terminated. If you want to print out a character use %c. Your line should look like this:
Also you might want to look and see how you are allocating strings. By specifying a size of sizeof(char *) it will only create a memory allocation the size of a pointer. If the string in rest is greater than that it will cause a buffer overrun when you do the strcpy.