linux文件读写的编程问题
(2012-06-06 21:25:46)
标签:
it
程序流程是:从字符设备文件中ds18b20读取buf,经运算后得到result,再将result存到自己创建的文件tresult中。
运行后发现程序能正常运行,但是用cat /tmp/tresult查看tresult时是一堆乱码。
程序如下
#include "stdio.h"
#include "sys/types.h"
#include "sys/ioctl.h"
#include "stdlib.h"
#include "termios.h"
#include "sys/stat.h"
#include "fcntl.h"
#include "sys/time.h"
main()
{
int fd;
int i,fd1,size;
unsigned char buf[2];
float result;
if((fd1 = open("/tmp/tresult.c", O_CREAT| O_RDWR|O_APPEND,0666 ))<0)
{
perror("open:");
exit(1);
}
else
printf("open file:tresult.c %d\n",fd);
if ((fd=open("/dev/ds18b20",O_RDWR | O_NDELAY | O_NOCTTY)) < 0)
{
printf("Open Device ds18b20 failed.\r\n");
exit(1);
}
else
{
printf("Open Device ds18b20 successed.\r\n");
while(1)
{
printf("read byte nums is %d\r\n",read(fd, buf, 3));
result = (float)buf[0];
result /= 16;
result += ((float)buf[1] * 16);
sleep(1);
if((size = write( fd1, &result, sizeof(result))) < 0)
{
perror("write:");
exit(1);
}
else
printf("Write:%.1f\n",result);
}
close(fd1);
close(fd);
}
}
后来知道是write写入的是二进制,所以不能用cat直接查看
所以写了如下程序
#include
#include
#include
#include
#include
#include
#include
#define MAXSIZE
int main(void)
{
int i,fd,size,len;
char buf_r[16];
buf_r[16] = '\0';
if((fd = open("/tmp/tresult.c",O_RDWR,0666 ))<0)
{
perror("open:");
exit(1);
}
else
printf("open file:tresult.c %d\n",fd);
// lseek( fd, 0, SEEK_SET );
if((size = read( fd, buf_r, 11))<0)
{
perror("read:");
exit(1);
}
else
printf("read form file:%f\n",buf_r);
if( close(fd) < 0 )
{
perror("close:");
exit(1);
}
else
printf("Close tresult.c\n");
exit(0);
}
但是read出来的也不对!
知道是fprint可以把数字编码转成字符再写入文件
所以试写了如下程序
main()
{
int fd,fd2;
int i,size,len;
FILE *fd1=NULL;
unsigned char buf[2];
float result;
char *buf1="Hello! I"m writing to this file!";
char buf_r[11];
int ii;
// len = strlen(buf1);
buf_r[10] = '\0';
if((fd2 =open("/tmp/tresult.c", O_CREAT| O_RDWR|O_APPEND,0666 ))<0)
{
perror("open:");
exit(1);
}
else
printf("open file:tresult.c %d\n",fd);
fd1=fopen("/armp/ds18b20/aa","a+");
if (fd1==NULL){
err("fopen() error,file");
}
if ((fd=open("/dev/ds18b20",O_RDWR | O_NDELAY | O_NOCTTY)) < 0)
{
printf("Open Device ds18b20 failed.\r\n");
exit(1);
}
else
{
printf("Open Device ds18b20 successed.\r\n");
// for(i=0;i<10;i++)
while(1)
{
printf("read byte nums is %d\r\n",read(fd, buf, 3));
result = (float)buf[0];
result /= 16;
result += ((float)buf[1] * 16);
printf("%.1f `C\r\n", result);
sleep(1);
fprintf(fd1,"%.1f",result);
if((size = write( fd2, &result, sizeof(result))) < 0)
{
perror("write:");
exit(1);
}
else
printf("Write:%.1f\n",result);
}
//lseek( fd1, 0, SEEK_SET );
close(fd1);
close(fd);
close(fd2);
}
}
发现fprint是有缓冲的,如果程序运行时用ctrl+c中断程序的话,文件aa可能没有被写入,cat aa后命令后
发现内容为空,若改为循环m次程序再自动退出则cat aa后能正常显示。
分享:
喜欢
0
赠金笔
加载中,请稍候......
评论加载中,请稍候...
发评论
登录名: 密码: 找回密码 注册记住登录状态
昵 称:
评论并转载此博文
发评论
以上网友发言只代表其个人观点,不代表新浪网的观点或立场。