This is my code
#include <stdio.h>
int main(int dict, char **jumbles) {
const char *j = *jumbles;
FILE *jumbles_file = fopen(j ,"r");
char jumbles_words[52];
while (fgets(jumbles_words, sizeof(jumbles_words), jumbles_file)) {
printf("%s", jumbles_words);
}
return 0;
}
Just ignore the parameter int dict
.
My point is to take input char **jumbles
and print out line by line. But when I run the program.
Output is unreadable. What are the reasons and how to fix this?
root@MSI:~# ./unscramble dictionary.txt jumbles.txt
��-o.2ck_chk_failGLIBC_2.34__/D=�.Dd����}.�dH�%(E���E�H��H��H��u˸���P
� 11.2.0-19ubuntu1) [email protected]_dtors_auxfini_array_entryay_entryEH_FRAME_HDRn@GLIBC_2.34niets@GLIBC_2.2.5andleIBC_2.2.5xa_finalize@GLIBC_2.2.5trtabontamemmenti
CodePudding user response:
The code you show uses argv[0] as input file. It is the binary program itself (normally), so you read binary gibberish.
Here's your code with some changes at the start, explanations in comments. The actual code may have other bugs (in particular, you don't check if fopen
succeeds), but this should solve the problem you ask about:
#include <stdio.h>
// Use normal main argument names
int main (int argc, char *argv[])
{
// Two arguments needed
if (argc != 3) {
puts("Two arguments expected!");
exit(1);
}
// arv[0] is program name
// argv[1] is dictionary file, ignored
const char *j = argv[2]; // jumbles file
// below code has no changes
FILE *jumbles_file = fopen(j ,"r");
char jumbles_words[52];
while(fgets(jumbles_words, sizeof(jumbles_words), jumbles_file)) {
printf("%s", jumbles_words);
}
return 0;
}