系统编程 一

open

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#include <errno.h>


int main(int argc, char const *argv[])
{
	int fd = open("main1.c", O_RDWR | O_CREAT,0777);

	if(-1 == fd)
	{
		printf("打开文件失败\n");
		printf("errno = %d\n",errno);
		perror("fd");
		exit(-1);

	}


	close(fd);
	return 0;
}

read

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>

#define SIZE 1024

int main(int argc, char const *argv[])
{
	int fd = open("main1.c", O_RDONLY);

	if(-1 == fd)
	{
		
		perror("fd");
		exit(-1);

	}

	char buf[SIZE+1];
	int  ret = 0;
	int count = 0;
	
	while((ret=read (fd,buf,SIZE)) != 0)
	{
		if (-1 == ret)
		{
			perror("ret");
			exit(-1);
		}
	
		count++;
		buf[ret] = '\0';
		printf("%s",buf );
	}
	printf("读取的数量=%d",count );


	close(fd);
	return 0;
}

write

#include <stdio.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>

#define SIZE 100

int main1(int argc, char const *argv[])
{
	int fd = open("tmp.text", O_RDWR | O_CREAT | O_TRUNC,0777);

	if (-1 == fd)
	{
		perror("open");
		exit(-1);
	}

	char buf[SIZE];

	while(1)
	{	
		fgets(buf , SIZE, stdin);

		if(strncmp(buf ,"end",3) == 0)
			break;
		
		ssize_t ret = write(fd, buf,strlen(buf));
		if (-1 == ret)
		{
			perror("write");
			exit(-1);
		}


	}
	close(fd);
	return 0;
}
int main2(int argc, char const *argv[])
{
	int fd1 = open("1.ppt", O_RDWR );
	int fd2 = open("2.ppt", O_RDWR | O_CREAT,0777);
	if(-1 == fd1 || -1 == fd2)
	{
		perror("open");
		exit(-1);
	}
	char buf[SIZE];
	ssize_t ret;
	while((ret = read(fd1,buf,SIZE)) != 0)
	{
		if(-1 == ret)
		{
			perror("read");
			exit(-1);
		}
		ret = write(fd2,buf,ret);
		if(-1 == ret)
		{
			perror("write");
			exit(-1);
		}

	}

	close(fd1);
	close(fd2);
	return 0;
}
int main(int argc, char const *argv[])
{
	int fd = open("tmp.text", O_RDWR | O_TRUNC );
	if(-1 == fd)
	{
		perror("open");
		exit(-1);
	}
	int a = 10;

	ssize_t ret = write (fd,&a,sizeof(int));

	if(-1 == ret)
	{
		perror("read");
		exit(-1);
	}

	printf("%d\n", a);

	close(fd);
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值