讨论套接字的过程讨论突然提及文件也许有些奇怪。但对于LINUX而言,socket操作和文件操作没有区别,Linux一切皆为文件,因此文件的IO函数也是socket的IO函数。(本文旨在给读者扩充知识,不必记住所谓的代码)
底层文件访问和文件描述符
- 底层:与标准无关底层提供的函数
- 文件描述符:系统分配给文件或者套接字的整数,windows被称为句柄,用来描述一种事件类型或者事物。
打开文件
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
int open(const char* path, int flag)
关闭文件
#include<unistd.h>
int close(int fd);
fd->需要关闭的文件或者套接字的文件描述符
将数据写入文件
#include<unistd.h>
ssize_t write(int fd, const void* buf, size_t nbytes);
fd显示数据传输对象的文件描述符。
将数据写入文件
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
void error_handling(char* message);
int main(void)
{
int fd;
char buf[]="Let's go!\n";
fd=open("data.txt", O_CREAT|O_WRONLY|O_TRUNC);
if(fd==-1)
error_handling("open() error!");
printf("file descriptor: %d \n", fd);
if(write(fd, buf, sizeof(buf))==-1)
error_handling("write() error!");
close(fd);
return 0;
}
void error_handling(char* message)
{
fputs(message, stderr);
fputc('\n', stderr);
exit(1);
}
/*
root@com:/home/swyoon/tcpip# gcc low_open.c -o lopen
root@com:/home/swyoon/tcpip# ./lopen
file descriptor: 3
root@com:/home/swyoon/tcpip# cat data.txt
Let's go!
root@com:/home/swyoon/tcpip#
*/
读取文件中的数据
#include <unistd.h>
ssize_t read(int fd, void* buf, size_t nbytes);
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#define BUF_SIZE 100
void error_handling(char* message);
int main(void)
{
int fd;
char buf[BUF_SIZE];
fd=open("data.txt", O_RDONLY);
if( fd==-1)
error_handling("open() error!");
printf("file descriptor: %d \n" , fd);
if(read(fd, buf, sizeof(buf))==-1)
error_handling("read() error!");
printf("file data: %s", buf);
close(fd);
return 0;
}
void error_handling(char* message)
{
fputs(message, stderr);
fputc('\n', stderr);
exit(1);
}
/*
root@com:/home/swyoon/tcpip# gcc low_read.c -o lread
root@com:/home/swyoon/tcpip# ./lread
file descriptor: 3
file data: Let's go!
root@com:/home/swyoon/tcpip#
*/
文件描述符与套接字
下面将同时创建文件和套接字,并用整数形态比较返回的文件描述符值。
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/socket.h>
int main(void)
{
int fd1, fd2, fd3;
fd1=socket(PF_INET, SOCK_STREAM, 0);
fd2=open("test.dat", O_CREAT|O_WRONLY|O_TRUNC);
fd3=socket(PF_INET, SOCK_DGRAM, 0);
printf("file descriptor 1: %d\n", fd1);
printf("file descriptor 2: %d\n", fd2);
printf("file descriptor 3: %d\n", fd3);
close(fd1);
close(fd2);
close(fd3);
return 0;
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。