《TCP/IP网络编程》课后练习第一章(自己写的,非标准答案)

文章介绍了套接字在网络数据传输中的作用,包括如何在Linux和Windows系统中使用,以及与文件I/O和标准I/O的区别。还提供了两个C语言示例(low_copy.c和ansi_copy.c)展示了文件复制的套接字操作。
摘要由CSDN通过智能技术生成

第一章

(1)

套接字的作用是网络数据传输

套接字本身就带有“连接”的含义,如果将其引申,则还可以表示两台计算机之间的网络连接

(2)

listen将套接字转化成可接收连接的状态,并为套接字设置挂起的连接队列的最大长度

accept受理连接请求

(3)

Linux系统中socket被认为是文件的一种,而在Windows系统中,要区分socket和文件

(4)

因为套接字的实现网络数据传输流程要求的

bind函数

(5)

套接字的文件描述符是套接字经过创建过程后系统分配给套接字的整数

Windows的套接字句柄是套接字创建完成后的返回值

(6)

文件I/O和标准I/O的区别_i/o效率指什么-CSDN博客

(7)

low_copy.c

#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>

#define BUF_SIZE 4096

void error_handling(char* message);

int main(int argc, char* argv[]){
	int fd0, fd1;
	char buf[BUF_SIZE];
	ssize_t count;
	
	if(argc != 3){
		printf("Usage : %s <ExistFilePath> <NewFilePath>\n", argv[0]);
		exit(1);
	}
	
	fd0 = open(argv[1], O_RDONLY);
	if(fd0 == -1)
		error_handling("ExistFile open() error!");
		
	count = read(fd0, buf, sizeof(buf));
	if(count == -1)
		error_handling("read() error!");
		
	close(fd0);
	
	fd1 = open(argv[2], O_CREAT | O_TRUNC | O_WRONLY);
	if(fd1 == -1)
		error_handling("NewFile open() error!");
		
	if(write(fd1, buf, count) == -1)
		error_handling("write() error!");
		
	close(fd1);
	
	return 0;
}

void error_handling(char* message){
	fputs(message, stderr);
	fputc('\n', stderr);
	exit(1);
}

ansi_copy.c

#include <stdio.h>
#include <stddef.h>
#include <stdlib.h>


#define BUFFER_SIZE 4096


int main(int argc, char* argv[]){

char buf[BUFFER_SIZE];

size_t count;

FILE *existFileHandle, *newFileHandle;


if(argc != 3){
    printf("Usage : %s <ExistFilePath> <NewFilePath>\n", argv[0]);
    exit(1);
}

existFileHandle = fopen(argv[1], "rb");

if(existFileHandle == NULL){
    fputs("existFileHandle fopen() error!\n", stderr);
    return 1;
}


count = 0;

count = fread(buf, 1, BUFFER_SIZE, existFileHandle);

if(count == 0){
    fputs("fread() error!\n", stderr);
    return 1;
}

fclose(existFileHandle);

newFileHandle = fopen(argv[2], "wb");

if(newFileHandle == NULL){
    fputs("newFileHandle fopen() error!\n", stderr);
    return 1;
}

if(fwrite(buf, 1, count, newFileHandle) != count){
    fputs("fwrite() error!\n", stderr);
    return 1;
}

fclose(newFileHandle);

return 0;

}

  • 10
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值