免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 2129 | 回复: 4
打印 上一主题 下一主题

求助读取文件错误 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2007-08-14 17:44 |只看该作者 |倒序浏览
char content[] = "abc\n";
         char buffer[sizeof("abc\n")];
         int port = 0;
         
         unsigned int filefd;//point to config file
         unsigned int serialfd;//point to serial port
         char * filename = "configfile";
         /*initialize serial port*/
         serialfd = SerialOpen(SERIAL_PORT_0 );
         SerialSetSpeed( SERIAL_PORT_0,115200);
         SerialSetMode( SERIAL_PORT_0, RS232_MODE);
         /*open file*/
         filefd = open(filename,O_RDWR|O_CREAT,10705) ;       
        /*write buf to file*/
         write (filefd,content,strlen(content));
          /*read file to buf*/
         if( read(filefd, buffer,strlen(content)) == -1)
         {
                  printf("read error");
         }
         else
         {
                 printf("%s",buffer);
         }
        exit(0);

}

在终端输出结果是乱码一个椭圆和六角菱形靠在一起,粘贴到emacs上显示是 ^D 。哪位大虾帮忙看看?

论坛徽章:
0
2 [报告]
发表于 2007-08-14 17:45 |只看该作者
buffer里面到底有啥啊?

论坛徽章:
0
3 [报告]
发表于 2007-08-14 17:47 |只看该作者
因为我没初始化?
我把buffer memset 后还是一样

[ 本帖最后由 wang9736 于 2007-8-14 17:51 编辑 ]

论坛徽章:
0
4 [报告]
发表于 2007-08-14 18:21 |只看该作者
原帖由 wang9736 于 2007-8-14 17:44 发表
char content[] = "abc\n";
         char buffer;
         int port = 0;
         
         unsigned int filefd;//point to config file
         unsigned int serialfd;//point to serial port
         char * filename = "configfile";
          ...

仔细看看自己的程序吧。。。
首先,你把窜口打开了什么都没干,其次,你往同一文件写了abc和一个\n,然后又读出来,buffer里没有‘\0’

论坛徽章:
0
5 [报告]
发表于 2007-08-15 09:39 |只看该作者

感谢回答,问题解决了!

的确是buffer没有用 ‘\0’ 结尾。加入
buffer[sizeof("abc\n") - 1] = ‘\0’;
就正常了!
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP