I am making a log function which stores in a file.
int log_func(char* msg)
{
int log_fd=0;
ssize_t write_ret=0;
int close_logfile_ret=0;
time_t result;
char error_msg[MAX_LOG_MSG_LEN]={' '};
log_fd = open("/home/pi/log_client.txt", O_CREAT|O_APPEND|O_WRONLY);
if(log_fd==-1)
{
printf("log failed !!----file open");
exit(1);
}
result = time(NULL);
snprintf(error_msg,MAX_LOG_MSG_LEN,"DALI_Server:%s:%s",asctime(localtime(&result)),msg);
write_ret = write(log_fd,error_msg,sizeof(error_msg));
if(write_ret == -1)
{
printf("log failed !!---- write");
exit(1);
}
close_logfile_ret = close(log_fd);
if(close_logfile_ret == -1)
{
printf("log failed !!---- close");
exit(1);
}
return 0;
}
Here the array error_msg has been initialized to 'space'. but when i write less characters to it I get following result.
input: log_func("DALI Server Started");log_func("File open/create...");
output in file:
DALI_Server:Thu Jan 16 16:53:56 2014
:DALI Server started ^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@DALI_Server:Thu Jan 16 16:54:06 2014
File open/create...^@^@^@^@^@^@^@^@^@..
Why are the garbage characters coming.
You write the whole error_msg
array, even the contents after the string terminator. Instead you should use strlen
to get the length of the string in the array, and only write that:
write_ret = write(log_fd, error_msg, strlen(error_msg));
来源:https://stackoverflow.com/questions/29536010/garbage-value-in-file-after-write