七十六. 非阻塞读终端
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#define MSG_TRY "try again\n"
// 非阻塞读终端
int main(void)
{
char buf[10];
int fd, n;
// /dev/tty --> 当前打开的终端设备
fd = open("/dev/tty", O_RDONLY | O_NONBLOCK);
if(fd < 0)
{
perror("open /dev/tty");
exit(1);
}
tryagain:
n = read(fd, buf, 10);
if (n < 0)
{
// 如果write为非阻塞,但是没有数据可读,此时全局变量 errno 被设置为 EAGAIN
if (errno == EAGAIN)
{
sleep(3);
write(STDOUT_FILENO, MSG_TRY, strlen(MSG_TRY));
goto tryagain;
}
perror("read /dev/tty");
exit(1);
}
write(STDOUT_FILENO, buf, n);
close(fd);
return 0;
}
七十七. stat函数介绍
七十八. 使用stat函数获取文件大小
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char* argv[])
{
struct stat buf_st;
int ret = stat("english.txt", &buf_st);
if(ret == -1)
{
perror("stat error");
exit(1);
}
printf("file size = %d\n", (int)buf_st.st_size);
return 0;
}
运行一下
[root@VM_0_15_centos file_op]# gcc size_stat.c -o size_stat
[root@VM_0_15_centos file_op]# ls
access.c chown.c ls-l.c rename.c size_stat.c strtol.c
chmod.c english.txt newstat size_stat stat.c truncate.c
[root@VM_0_15_centos file_op]# ./size_stat
file size = 109055
七十九. st_mode如何获取文件类型和权限
八十. st_mode如何获取文件类型和权限——代码
首先是type_stat.c
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char* argv[])
{
struct stat buf_st;
int ret = stat("english.txt", &buf_st);
if(ret == -1)
{
perror("stat error");
exit(1);
}
if((buf_st.st_mode & S_IFMT) == S_IFREG)
{
printf("这个文件是一个普通文件\n");
}
return 0;
}
然后运行一下
[root@VM_0_15_centos file_op]# vim type_stat.c
[root@VM_0_15_centos file_op]# gcc type_stat.c -o type_stat
[root@VM_0_15_centos file_op]# ls
access.c chown.c ls-l.c rename.c size_stat.c strtol.c type_stat
chmod.c english.txt newstat size_stat stat.c truncate.c type_stat.c
[root@VM_0_15_centos file_op]# ./type_stat
这个文件是一个普通文件
然后接下来我们处理的是文件权限的查看。
先是mode_stat.c
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char* argv[])
{
struct stat buf_st;
int ret = stat("english.txt", &buf_st);
if(ret == -1)
{
perror("stat error");
exit(1);
}
//所有者对文件的操作权限
if(buf_st.st_mode & S_IRUSR)
{
printf(" r");
}
if(buf_st.st_mode & S_IWUSR)
{
printf(" w");
}
if(buf_st.st_mode & S_IXUSR)
{
printf(" x");
}
return 0;
}
运行
[root@VM_0_15_centos file_op]# vim mode_stat.c
[root@VM_0_15_centos file_op]# gcc mode_stat.c -o mode_stat
[root@VM_0_15_centos file_op]# ls
access.c english.txt mode_stat.c size_stat strtol.c type_stat.c
chmod.c ls-l.c newstat size_stat.c truncate.c
chown.c mode_stat rename.c stat.c type_stat
[root@VM_0_15_centos file_op]# ./mode_stat