写入后文件中的垃圾值 [英] Garbage Value in File after write
本文介绍了写入后文件中的垃圾值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在制作一个存储在文件中的日志功能.
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;
}
这里,数组error_msg已被初始化为'space'.但是当我写更少的字符时 我得到以下结果.
Here the array error_msg has been initialized to 'space'. but when i write less characters to it I get following result.
输入:log_func("DALI Server Started");log_func("File open/create...");
在文件中输出:
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...^@^@^@^@^@^@^@^@^@..
为什么垃圾字符来了
推荐答案
您编写了整个 error_msg
数组,甚至是字符串终止符之后的内容.相反,您应该使用strlen
来获取数组中 string 的长度,并且只写:
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));
这篇关于写入后文件中的垃圾值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文