UNIX系统编程2<C代码>1

UNIX系统编程2<C代码>1

        配合UNIX系统编程2<笔记>使用。

01:tree:
#include <stdio.h>
#include <dirent.h>
#include <string.h>

static int list_dir(const char *dirname, size_t width)
{
	DIR *dirp = opendir(dirname);
	if (!dirp) {
		printf("%*s<error opening dir \"%s\">\n", width, "", dirname);
		goto err_opendir;
	}

	chdir(dirname);

	struct dirent *p = NULL;
	while (p = readdir(dirp)) {
		//排除掉.和..
		if (!strcmp(p->d_name, ".") || !strcmp(p->d_name, "..")) {
			continue;
		}
		//当前遍历到文件夹
		if (p->d_type == DT_DIR) {
			printf("%*s[%s]\n", width, "", p->d_name);
			list_dir(p->d_name, width+4);
		} else {
			printf("%*s%s\n", width, "", p->d_name);
		}
	}

	chdir("..");

	closedir(dirp);

	return 0;

err_opendir:
	return -1;
}

int main(int argc, char **argv)
{
	switch (argc) {
		case 1:
			printf("%s\n", ".");
			list_dir(".", 4);
			break;
		case 2:
			printf("%s\n", argv[1]);
			list_dir(argv[1], 4);
			break;
		default:
			fprintf(stderr, "wrong arg\n");
			break;
	}

	return 0;
}
02ls:
#include <stdio.h>
#include <dirent.h>
#include <sys/stat.h>
#include <unistd.h>
#include <string.h>
#include <time.h>

#define PATH_LEN 50
static char path[PATH_LEN] = {0};
static struct stat info;

static int list_dir(const char *dirname)
{
	DIR *dirp = opendir(dirname);
	if (!dirp) {
		perror("opendir");
		goto err_opendir;
	}

	strncpy(path, dirname, PATH_LEN);

	struct dirent *p = NULL;
	while (p = readdir(dirp)) {
		strncat(path, p->d_name, PATH_LEN);
		//printf("path=%s\n", path);
		stat(path, &info);
		printf("%o ", info.st_mode);
		printf("%d ", info.st_uid);
		printf("%d ", info.st_gid);
		printf("%ld ", info.st_size);

		memset(path, 0, PATH_LEN);
		strncpy(path, ctime(&info.st_atime), PATH_LEN);
		*(path + strlen(path) - 1) = 0;

		printf("%s ", path);
		printf("%s", p->d_name);
		if (p->d_type == DT_DIR) {
			printf("/\n");
		} else {
			printf("\n");
		}
		memset(path, 0, PATH_LEN);
	}

	closedir(dirp);

	return 0;

err_opendir:
	return -1;
}

int main(int argc, char **argv)
{
	switch (argc) {
		case 1:
			list_dir("./");
			break;
		case 2:
			list_dir(argv[1]);
			break;
		default:
			fprintf(stderr, "不能识别的指令用法\n");
			break;
	}

	return 0;
}
03unlink:
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>

#define TMP_FILE "tmp"

int main()
{
	//创建
	int fd = open(TMP_FILE, O_RDWR | O_CREAT | O_TRUNC, 0664);
	if (fd < 0) {
		perror("creat");
		goto err_creat;
	}

	unlink(TMP_FILE); //删除该文件,文件系统下不能再看见这个文件,也就不能再打开

	int fd1 = open(TMP_FILE, O_RDWR);
	if (fd1 < 0) {
		perror("open");
	}

	unsigned char buf[] = "hello world\n";
	if (write(fd, buf, sizeof(buf)) < 0) {
		perror("write");
	}//write是成功的,说明在执行unlink后,fd还是可以使用,直到close(fd)为止

	sleep(5);
	
	close(fd);

	return 0;

err_creat:
	return -1;
}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值