UNXI系统编程1<C代码>
和UNXI系统编程1<笔记>配套.具体如下:
01open:
********************************
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
int main()
{
int fd = open("open.c", O_RDONLY);
if (fd < 0) {
perror("open");
goto err_open;
}
int fd_out = open("tmp.c", O_WRONLY | O_CREAT | O_TRUNC, 0664);
if (fd_out < 0) {
perror("open fd_out");
goto err_open_fd_out;
}
off_t file_size = lseek(fd, 0, SEEK_END);
printf("file size = %ld\n", file_size);
lseek(fd, 0, SEEK_SET);
#define BUF_SIZE 20
unsigned char buf[BUF_SIZE] = {0};
size_t r_count = 0;
while (r_count = read(fd, buf, sizeof(buf))) {
write(STDOUT_FILENO, buf, r_count);
write(fd_out, buf, r_count);
}
close(fd_out);
close(fd);
return 0;
err_open_fd_out:
close(fd);
err_open:
return -1;
}
*****************************
02opendir:
#include <stdio.h>
#include <dirent.h>
#include <unistd.h>
int main()
{
chdir("..");
DIR *dirp = opendir(".");
if (!dirp) {
perror("opendir");
goto err_opendir;
}
struct dirent *p = NULL;
while (p = readdir(dirp)) {
printf("=====%s====\n", p->d_name);
printf("d_off=%ld\n", p->d_off);
printf("telldir=%ld\n", telldir(dirp));
printf("d_reclen=%d\n", p->d_reclen);
}
printf("\n====seekdir====\n");
seekdir(dirp, 1106281852);
p = readdir(dirp);
printf("=====%s====\n", p->d_name);
closedir(dirp);
return 0;
err_opendir:
return -1;
}
03align:
#include <stdio.h>
//最大成员和cpu字长取最小值,整个结构体大小必须是该值的倍数
struct foo {
int a;
short b;
char c;
long long d; //每个成员本身大小和cpu字长取最小值,该成员的起始地址必须是该值的倍数
char e;
};
struct foo1 {
char a;
};
struct foo2 {
};
#pragma pack(1) //可以更改为小于cpu字长的对齐规则,用于一些协议的使用,当数字大于等于cpu字长时,没有效果
struct foo3 {
int a;
short b;
long long d;
char e;
};
#pragma pack()
int main()
{
printf("%d\n", sizeof(struct foo));
printf("%d\n", sizeof(struct foo1));
printf("%d\n", sizeof(struct foo2));
printf("%d\n", sizeof(struct foo3));
printf("%*s%d\n", 8, "", 100);
return 0;
}
04:
#include <stdio.h>
#include <string.h>
#include <fcntl.h>
#include <errno.h>
extern int errno; //全局变量,每个进程中有唯一的一个变量,记录错误码
int main()
{
int fd = open("abc", O_RDONLY);
if (fd < 0) {
perror("open fd");
fprintf(stderr, "strerror: %s\n",
strerror(errno));
goto err_open;
}
close(fd);
return 0;
err_open:
return -1;
}
05
#include <stdio.h>
extern char **environ;
int main()
{
char **str = environ;
while (*str) {
printf("%s\n", *str);
str++;
}
return 0;
}