打印

linux write 问题

[复制链接]
1456|1
手机看帖
扫描二维码
随时随地手机跟帖
跳转到指定楼层
楼主
急驰的蚂蚁|  楼主 | 2010-8-19 16:26 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>

char buf[7];
int main()
{
        int fd,size,nothing;
       
        int data0,data1;
        fd = open("test",O_CREAT |O_SYNC |O_RDWR ,0666); //|O_TRUNC  
        if(fd <0)
        {
                printf("open error!\n");
                return -1;
        }
        lseek(fd,SEEK_SET,0);
        size = write(fd,"test",5);
        printf("write %d byte\n",size);
        lseek(fd,SEEK_SET,0);
        size = read(fd,buf,5);
        printf("read %d byte\n",size);
        printf("buf[0] = %c,buf[1] = %c,buf[2] = %c \n",buf[0],buf[1],buf[2]);

        close(fd);
        return 0;
}
运行结果:
write 5 byte
read 5 byte
buf[0] = t,buf[1] = e,buf[2] = s





#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>

char buf[7];
int main()
{
        int fd,size,nothing;
       
        int data0,data1;
        fd = open("test",O_CREAT |O_SYNC |O_RDWR ,0666); //|O_TRUNC  
        if(fd <0)
        {
                printf("open error!\n");
                return -1;
        }
        lseek(fd,SEEK_SET,1);         //change,frist is 0
        size = write(fd,"test",5);
        printf("write %d byte\n",size);
        lseek(fd,SEEK_SET,1);         //change,frist is 0
        size = read(fd,buf,5);
        printf("read %d byte\n",size);
        printf("buf[0] = %c,buf[1] = %c,buf[2] = %c \n",buf[0],buf[1],buf[2]);

        close(fd);
        return 0;
}

运行结果:
write 5 byte
read 0 byte
buf[0] = ,buf[1] = ,buf[2] =


每次运行前都会把test文件删除

为什么第二个代码不能得到和第一个代码的数据呢?
我在第二个代码read前加入system("sync");也不行
应该不是空洞的问题和同步的问题吧
实在找不到答案了
各位高手有什么看法

相关帖子

沙发
急驰的蚂蚁|  楼主 | 2010-8-19 17:54 | 只看该作者
#include <sys/types.h>
       #include <unistd.h>

       off_t lseek(int fildes, off_t offset, int whence);


我的lseek 函数用错了

使用特权

评论回复
发新帖 我要提问
您需要登录后才可以回帖 登录 | 注册

本版积分规则

13

主题

66

帖子

0

粉丝