In write
you have a problem, you need to pass the length of the string in the count
argument, i.e. strlen(user_input)
instead of 20:
write(fileID, user_input, strlen(user_input));
Otherwise it will write all 20 characters regardless of the size of the string stored in user_input
. e.g if the string has 8 characters it will write those 8 characters plus the null terminator plus whatever garbage values are stored in the remaining elements of the char array until the size of 20.
Also to note that the actual length of the string is never 20 because of the way you use fgets
, it will have at most 19 characters + the null-byte(more details ahead), this null byte is also being written to the file.
Keep in mind that when you read the string from the file you'll need to null terminate it by hand, the above write
will not store the null byte in the file.
Regarding fgets
, it will store the null byte \0
in the last character of the destination buffer, so if you pass the size of 20, it will store at most 19 characters + the null byte. The good practice is to use the size of the destination buffer:
fgets(user_input, sizeof user_input, stdin);
Also to note is that fgets
stores the \n
newline character present in the input stream.
A string parsed with fgets
will look like:
+---+---+---+---+---+---+----+----+
|'s'|'t'|'r'|'i'|'n'|'g'|'\n'|'\0'|
+---+---+---+---+---+---+----+----+
Unless \n
is to be stored in the last element of the destination buffer in which case it will be left in the stdin
buffer, and in its place will be a \0
.
You can remove this \n
character if you wish to do so with:
user_input[strcspn(user_input, "\n")] = '\0'; //#include <string.h>
Here is a Live Demo with the issues fixed.