linux关机前写文件乱码,linux系统在往文件写入之后,读出来后面却又乱码原因...

===================================================================================================================================

linux系统下文件写入,读取出现乱码原因

前一段时间做好了FL2440开发板eeprom的驱动,今天在编写往eeprom中读写的测试程序,可以往里面写入,但是在读出来的时候会出现乱码问题。

有问题的代码

#include #include #include #include #include #include #include /********************************************************************************

* Description:

* Input Args:

* Output Args:

* Return Value:

********************************************************************************/

int main (int argc, char **argv)

{

int fd, ret, opt;

char a_data[5];

fd = open("/sys/devices/platform/s3c2440-i2c/i2c-0/0-0050/eeprom",O_RDWR);

while((opt=getopt(argc,argv,"rw:"))!=-1)

{

switch(opt)

{

case 'r':

lseek(fd,0,SEEK_SET);

ret = read(fd,a_data,5);

printf("the information we read from eeprom is %s !\n",a_data);

break;

case 'w':

strcpy(a_data,optarg);

lseek(fd,0,SEEK_SET);

ret = write(fd,a_data,5);

break;

}

}

return 0;

} /* ----- End of main() ----- */

有问题的结果:

>:./write -w 12345

>:./write -r

the information we read from eeprom is 12345 @

>:./write -r

the information we read from eeprom is 12345?@

****************************************************************************************************************

出现问题的原因:

1.是没有将读的缓存a_data先memset设置为0

2.在字符串的输出时以“\0”为结束标志的,我在字符串里面装5个字符,就要申请6个字符的空间,最后一个放置“\0”

****************************************************************************************************************

修改之后的程序

#include #include #include #include #include #include #include #include /********************************************************************************

* Description:

* Input Args:

* Output Args:

* Return Value:

********************************************************************************/

int main (int argc, char **argv)

{

int fd, ret, opt;

char a_data[6];

memset(a_data,0,6);

fd = open("/sys/devices/platform/s3c2440-i2c/i2c-0/0-0050/eeprom",O_RDWR);

while((opt=getopt(argc,argv,"rw:"))!=-1)

{

switch(opt)

{

case 'r':

lseek(fd,0,SEEK_SET);

ret = read(fd,a_data,5);

printf("the information we read from eeprom is %s !\n",a_data);

break;

case 'w':

strcpy(a_data,optarg);

lseek(fd,0,SEEK_SET);

ret = write(fd,a_data,5);

break;

}

}

return 0;

} /* ----- End of main() ----- */

测试的结果:

>:./write -w 12345

>:./write -r

the information we read from eeprom is 12345 !

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值