Linux中,socket 也是被认为是文件的一种
window中,需要区分socket和文件
- 文件描述符:window中叫文件句柄;可以理解成分配的ID
- socket经过创建的过程中才会被分配文件描述符
文件操作
- 打开文件 int open(const char *path, int flag),flag是打开的模式,多个模式用OR连接,返回的就是文件描述符。(#include
#include #include ) - 关闭文件int close(int fd),这个同样可以关闭socket。(#include
) - 将数据写入文件:ssize_t write(int fd, const void *buf, size_t nbytes);,(#include
) - size_t 是 unsigned int,ssize_t 是 signed int
读写文件操作
#include#include #include #include #include void error_handling(char *message); int main(void) { int fd; char buf[] = "Let's go! n"; // 设置权限 umask(0000); if(creat("data.txt", 0777) == -1) error_handling("creat() errorn"); // 写入数据 fd = open("data.txt", O_CREAT|O_WRONLY|O_TRUNC); if(fd == -1) error_handling("write open() errorn"); printf("file descriptor %dn", fd); if(write(fd, buf, sizeof(buf)) == -1) error_handling("write() errorn"); printf("write over.n"); close(fd); // 读取数据 fd = open("data.txt", O_RDONLY); if(fd == -1) error_handling("read open() errorn"); char read_buf[100]; if(read(fd, read_buf, sizeof(read_buf)) == -1) error_handling("read() errorn"); printf("file data is %sn", read_buf); close(fd); return 0; } void error_handling(char *message) { perror(message); exit(1); }
注:
- 如果提示没有权限,可以参考 Permission denied: https://blog.csdn.net/aicamel/article/details/80922459,在创建文件的时候,设置权限
- 这些文件IO操作同样适用于socket
- 文件描述符从3开始,从小到大编号,因为0、1、2被分配给了标准IO描述符
同时创建文件和套接字,打印出对应的文件描述符
#include#include #include #include #include #include void error_handling(char *message); int main(void) { int fd1, fd2, fd3; char *file_name = "data.dat"; // 设置权限 umask(0000); if(creat(file_name, 0777) == -1) error_handling("creat() errorn"); fd1 = socket(PF_INET, SOCK_STREAM, 0); fd2 = open(file_name, O_CREAT|O_WRONLY|O_TRUNC); fd3 = socket(PF_INET, SOCK_STREAM, 0); printf("file descripor 1: %dn", fd1); printf("file descripor 2: %dn", fd2); printf("file descripor 3: %dn", fd3); close(fd1); close(fd2); close(fd3); return 0; } void error_handling(char *message) { perror(message); exit(1); }
其他:
- 常用的flag常量值:只读(O_RDONLY),只写(O_WRONLY),读写(O_RDWR),必要时创建文件(O_CREAT),删除现有数据(O_TRUNC),追加模式(O_APPEND)
- 0、1、2文件描述符分别是标准输入、输出、错误



