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;
}
收藏 打印