poi 需要 inux 文件 name fcn flag exc 文件描述符
代码:
- #include < stdio.h > #include < string.h > #include < fcntl.h >
- /*************基本的函数API********************
- int open(const char *pathname, int oflag, int perms)
- oflag:
- O_RDONLY 只读
- O_WRONLY 只写
- O_RDWR 读写
- O_APPEND 追加
- O_CREAT 创建
- O_EXCL 测试
- O_TRUNC 删除
- perms:
- 被打开的文件的存取权限,采用8进制
- int close(int fd)
- ssize_t read(int fd, void *buf, size_t count)
- fd:
- 文件描述符
- buf:
- 指定存储器读取数据的缓冲区
- count:
- 指定读取数据的字节数
- ssize_t write(int fd, void *buf, size_t count)
- fd:
- 文件描述符
- buf:
- 指定存储器读取数据的缓冲区
- count:
- 指定读取数据的字节数
- off_t lseek(int fd, off_t offset, int whence)
- fd:
- 文件描述符
- offset:
- 偏移量,每一读写操作需要移动的字节数,可向前、可向后
- count:
- 当前位置的基点:
- SEEK_SET(当前位置是文件的开头)
- SEEK_CUR(当前位置为文件指针的位置,新位置为当前位置加上偏移量)
- SEEK_END(当前位置问文件的尾部,新位置为文件大小加上偏移量的大小)
- **********************************************/
- int main(void) {
- int fd,
- len;
- char * buf = "Hello World!\n",
- Out[30];
- fd = open("a.txt", O_CREAT | O_TRUNC | O_RDWR, 0600);
- printf("open file:a.txt fd = %d\n", fd);
- len = strlen(buf);
- int size = write(fd, buf, len);
- close(fd);
- //Begin to read the file
- fd = open("a.txt", O_RDWR, 0600);
- lseek(fd, 0, SEEK_SET); //Before to read the file,you should call the function to make the fd point to begin of files
- size = read(fd, Out, 12);
- printf("size = %d\nread from file:\n %s\n", size, Out);
- close(fd);
- return 0;
- }
未完待续~
Linux下C语言的文件操作
来源: http://www.bubuko.com/infodetail-2338140.html