Linux中,socket 也是被认为是文件的一种
window中,需要区分socket和文件
- 文件描述符:window中叫文件句柄;可以理解成分配的ID
- socket经过创建的过程中才会被分配文件描述符
文件操作
- 打开文件
,flag是打开的模式,多个模式用OR连接,返回的就是文件描述符。(#include <sys/types.h> #include <sys/stat.h> #include <fcntl.h>)int open(const char *path, int flag)
- 关闭文件
,这个同样可以关闭socket。(#include <unistd.h>)int close(int fd)
- 将数据写入文件:
,(#include <unistd.h>)ssize_t write(int fd, const void *buf, size_t nbytes);
- size_t 是 unsigned int,ssize_t 是 signed int
读写文件操作
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/stat.h>
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() error\n");
// 写入数据
fd = open("data.txt", O_CREAT|O_WRONLY|O_TRUNC);
if(fd == -1)
error_handling("write open() error\n");
printf("file descriptor %d\n", fd);
if(write(fd, buf, sizeof(buf)) == -1)
error_handling("write() error\n");
printf("write over.\n");
close(fd);
// 读取数据
fd = open("data.txt", O_RDONLY);
if(fd == -1)
error_handling("read open() error\n");
char read_buf[100];
if(read(fd, read_buf, sizeof(read_buf)) == -1)
error_handling("read() error\n");
printf("file data is %s\n", 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 <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/stat.h>
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() error\n");
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: %d\n", fd1);
printf("file descripor 2: %d\n", fd2);
printf("file descripor 3: %d\n", 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文件描述符分别是标准输入、输出、错误