Linux程序设计第二版练习题(第五章)

很久以前的学习过的一本书,这部书比较基础。
以下只是个人的做法,仅供参考。
1、设计一个程序,要求打开文件“pass“,如果没有这个文件,权限设置为只有所有者有只读权限。

#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
void main()
{
	int fd;
	if((fd=open("pass",O_CREAT))<0)
	{
		printf("文件不存在\n");
	}
	printf("创建文件pass,文件描述符为:%d\n",fd);
	chmod("pass",S_IRUSR|S_IWUSR);
}

2、设计一个程序,要求新建一个文件”hello“,利用write函数将”Linux下C软件设计”字符串写入该文件。

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
void main()
{
	int fd,twrite;
	if((fd=open("hello",O_CREAT|O_TRUNC|O_WRONLY,0600))<0)
	{
		printf("打开文件出错");
		exit(1);
	}
	char str[]="Linux下C软件设计";
	if((twrite=write(fd,str,sizeof(str)))<0)
	{
		printf("写入文件出错");
		exit(1);
	}
	close(fd);
	exit(0);
}

3、设计一个程序,要求用read函数读取系统文件"/etc/passwd",并在终端中显示输出。

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
void main()
{
	int fd,rtype,wtype;
	char str[30];
	if((fd=open("/etc/passwd",O_RDONLY))<0)
	{
		printf("读取文件失败!");
		exit(1);
	}
	while((rtype=read(fd,str,30))>0)
	{
		if((wtype=write(STDOUT_FILENO,str,rtype))<0)
			printf("写入文件出错");
	}
	close(fd);
}


4、设计一个程序,要求打开文件“pass”,如果没有这个文件,新建此文件,再读取系统文件“/etc/passwd”,把文件中的内容写入“pass”文件。

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
void main()
{
	int fdsrc,fddes,nbytes,wtype;
	char str[30];
	if((fddes=open("pass",O_CREAT|O_TRUNC|O_WRONLY,0600))<0)
	{
		printf("打开(创建)文件pass失败!");
		exit(1);
	}
	if((fdsrc=open("/etc/passwd",O_RDONLY))<0)
	{
		printf("打开文件失败!");
		exit(1);
	}
	while((nbytes=read(fdsrc,str,30))>0)
	{
		if((wtype=write(fddes,str,30))<0)
			printf("写入文件失败");
	}
	close(fdsrc);
	close(fddes);
}

6、设计一个程序,要求新建一个目录,预设权限为—x–x--x。

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
void main()
{
	system("mkdir exercise");
	chmod("exercise",S_IXUSR|S_IXGRP|S_IXOTH);
}
	

7、设计一个程序,要求为“/bin/ls”文件建立一个软连接“ls1”和一个硬链接为“ls2”,并查看两个链接文件和“/bin/ls”文件。

#include <stdlib.h>
#include <unistd.h>
void main()
{
	symlink("/bin/ls","ls1");
	link("/bin/ls","ls2");
	system("ls -l /bin/ls");
	system("ls -l ls1");
	system("ls -l ls2");
}

  • 15
    点赞
  • 90
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值