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

来源:互联网 发布:苹果手机网络无法连接 编辑:程序博客网 时间:2024/05/18 03:23

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

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

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


有问题的代码

#include <stdio.h>#include <string.h>#include <sys/ioctl.h>#include <stdlib.h>#include <fcntl.h>#include <sys/io.h>#include <getopt.h>/******************************************************************************** *  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 <stdio.h>#include <string.h>#include <sys/ioctl.h>#include <stdlib.h>#include <fcntl.h>#include <sys/io.h>#include <getopt.h>#include <memory.h>/******************************************************************************** *  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
原创粉丝点击