I am doing pset2 hacker edition. I am trying to read a line of string from "/usr/share/dict/words" as per pset specification using fgets() function but instead of reading the full line it is only reading first three characters of the string & adding an extra newline in the end of string. Please help me how can I read a full line of string. Also I'd like to say I've tried using getline() function but with the header file #include which is compulsory to invoke crypt() function its header files are ignored or something else I don't know & is giving me the error implicit function declaration of grtline() function.
First consider the size this elements have in the cs50 appliance.
- char = 1byte
- char* (pointer) = 4bytes
You are declaring word and initializing it with the pointer returned by malloc, that is fine. But you are allocating:
malloc(sizeof(char*) * 1);
You need to realize that the sizeof(char*) is the size of a pointer, which is 4bytes in the cs50 appliance, and the same for the call to fgets:
fgets(word, sizeof(word), fp)
the second argument of fgets() specifies the maximum number of characters to be read from the stream including the null character. So you are reading the sizeof(word) which is 4 per the declaration of word, 3 characters plus the null character.
You need to initialize word with enough space to store the longest word in the dictionary plus the null character, and then you can read the same amount in fgets().