一. open()&close()
#include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <stdio.h> int main() { int fd; fd = open("abc.txt", O_CREAT|O_RDWR, 0777); // 若flag中使用了O_CREAT,则需要指定第三个参数访问权限 if (fd < 0) printf("file create failure"); printf("current fd is: %d ", fd); close(fd); return 0; }
二.read()&write()
write.c
#include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <string.h> static const char *str = "http://www.baidu.com "; int main() { int fd; fd = open("cde.txt", O_CREAT|O_RDWR|O_APPEND, 0777); write(fd, str, strlen(str)); close(fd); return 0; }
read.c
#include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <string.h> #include <unistd.h> #include <stdio.h> int main() { char tmp[30]; char str[1024]; int wr_fd; wr_fd = open("aaa.txt", O_CREAT|O_WRONLY|O_APPEND, 0777); int rd_fd; rd_fd = open("cde.txt", O_RDONLY); int total = 0, len; while((len = read(rd_fd, tmp, 30))) { strncpy(str+total, tmp, len); total+=len; } str[total-1] = '