#include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> int open(const char *pathname, int flags); int open(const char *pathname, int flags, mode_t mode);
例子:模拟touch命令linux
#include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> int main(int argc, char* argv[]){ int fd = open(argv[1], O_RDONLY|O_CREAT|O_EXCL, 0666); close(fd); return 0; }
0666 & ~0002 = 0664,因此建立出来的文件的权限是:-rw-rw-r--c++
#include <unistd.h> ssize_t read(int fd, void *buf, size_t count);
#include <unistd.h> ssize_t write(int fd, const void *buf, size_t count);
例子:模拟cat命令微信
#include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> int main(int argc, char* argv[]){ int fd = open(argv[1], O_RDONLY); char buf[64] = {0}; int ret = 0; while((ret = read(fd, buf, sizeof buf)) > 0){ write(STDOUT_FILENO, buf, ret); } close(fd); return 0; }
#include <sys/types.h> #include <unistd.h> off_t lseek(int fd, off_t offset, int whence);
例子1:把字符串“helloworld”写入一个文件,而后读取这个文件,把“helloworld”从文件中读取出来,并打印到终端。学习
#include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> int main(int argc, char* argv[]){ int fd = open(argv[1], O_RDWR|O_CREAT, 0666); write(fd, "helloworld\n", 11); //这里必须使用lseek,来调整文件指针的位置,设置文件指针设置到文件的开始位置。 lseek(fd, 0, SEEK_SET); char buf[20] = {0}; int ret = read(fd, buf, sizeof buf); write(STDOUT_FILENO, buf, ret); close(fd); return 0; }
例子2:计算文件的大小指针
#include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <stdio.h> #include <unistd.h> int main(int argc, char* argv[]){ int fd = open(argv[1], O_RDWR); //open后,文件指针的位置在文件开头 //由于:lseek返回当前位置到开始位置的长度 //因此用lseek移动到了文件末尾,这时lseek的返回值就是文件的大小 int ret = lseek(fd, 0, SEEK_END); printf("file size:%d\n", ret); close(fd); }
例子3:建立文件大小为1024的文件code
#include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <stdio.h> #include <unistd.h> int main(int argc, char* argv[]){ int fd = open(argv[1], O_WRONLY|O_CREAT, 0666); //打开后文件指针在文件的开始位置,而后从开始位置移动1023个字节,而后再调用write, //注意不调用后面的write的话,建立的文件的大小是为0的。 lseek(fd, 1023, SEEK_SET); write(fd, "a", 1); close(fd); }