#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");也不行
应该不是空洞的问题和同步的问题吧
实在找不到答案了
各位高手有什么看法 |