基于Linux文件操作----网络编程(linux----C)

基于Linux文件操作----网络编程(linux----C)

1、分配给标准输入输出及标准错误的文件描述符


(1)打开文件

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

函数:int open(const char *path,int flag);

成功时返回文件描述符,失败时返回-1。

path:文件名的字符串地址。flag:文件打开模式信息。


(2)关闭文件

#include <unistd.h>

函数:int close(int fd);

成功时返回0,失败时返回-1。

(3)将数据写入文件

#include  <unistd.h>

函数:ssize_t write(int fd,const void *buf,size_t  nbytes);

其中,ssize_t是通过typedef声明的signed  int 类型。

成功时返回写入的字节数,失败时返回-1。

fd:显示数据传输对象的文件描述符。buf:保存要传输数据的缓冲地址值。nbytes:要传输数据的字节数。


编写程序:创建新文件并保存数据

low_open.c代码:

#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);
}
编译与运行
编译:gcc low_open.c -o lopen 
运行:./lopen



读取文件
#include <unistd.h>
函数 :ssize_t read(int fd,void *buf,size_t nbytes);

成功时返回接收的字节数(但遇到文件结尾则返回0),失败时返回-1。

fd:显示数据接收对象的文件描述符。buf:保存接收数据的缓冲地址值。nbytes:要接收数据的最大字节数。

编程:通过read函数读取data.txt中保存的数据。
low_read.c代码:
#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);
}
编译:gcc low_read.c -o lread
运行:./lread
结果:


文件描述符与套接字
编程:同时创建文件和套接字,并用整数型态比较返回的文件描述符。
fd_seri.c代码:
#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;
}
编译:gcc fd_seri.c -o fds
运行:./fds
结果:

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值