detect the case of fgets fail
detect the case of writing fail
avoid array out of range
fixed a warning
added pthread for linux