#include <stdio.h>
2 #include <fcntl.h>
3 #include <unistd.h>
4 #define MAXSIZE 50
5 char buf1[MAXSIZE] = "sadfljlkj;jjjlkj;aj";
6 char buf2[MAXSIZE];
7 int main(int argc, char *argv[])
8 {
9 int fd;
10 /*if((fd = open("test.c", O_RDWR | O_CREAT | O_APPEND, S_IRWXU)) < 0 ); */
11 if((fd = creat("test2",S_IRWXU )) < 0)
12 printf("the file is not opened!\n");
13 if(write(fd ,buf1,sizeof(buf1)) != sizeof(buf1) )
14 printf("write wrong!\n");
15 close(fd);
16 if((fd =open("test2",O_RDONLY)) < 0)
17 printf("the file is not opened!\n");
18 /* if(lseek(fd,0,0) == -1)
19 printf("cannot seek\n");
20 */
21 if(read(fd,buf2,10) != 10)
22 printf("read wrong!\n");
printf("%s\n",buf2);
24 close(fd);
25 }
非常蹩脚的程序,一步一步来吧
(1)write完后直接read,犯了文件偏移量的错误,因为write后偏移量到了文件末尾,自然是读不出来的,需要lseek,但是我试过了lseek,还是read不出来,看被注释的代码
(2) open 不对,我尝试 直接open一个已存在的文件,如果不存在就创建,存在就在文件末尾添加数据,但是失败了。
继续学习,把一个文件拷贝给另外一个文件 ,小技巧是while,数目可以随意,如果到了末尾就会返回零,退出循环
1 #include <stdio.h>
2 #include <fcntl.h>
3 #include <unistd.h>
4 int main(int argc, char *argv[])
5 {
6 int fd1, fd2;
7 char *buf;
8 size_t num;
9 if((fd1 = open(argv[1],O_RDONLY,S_IRWXU)) < 0)
10 printf("open wrong! \n");
11 if( (fd2 = open(argv[2],O_WRONLY | O_CREAT, S_IRWXU )) < 0)
12 printf("open wrong too !\n");
13 while(num = read(fd1, buf, 20))
14 write(fd2, buf, 20);
15 close(fd1);
16 close(fd2);
17
18 }