一、作业
第一题: 使用read函数读取一个文件中的所有内容 使用printf函数将读取到的内容,输出到终端 以及 写入另一个文件中
代码如下:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <pthread.h>
#include <semaphore.h>
#include <wait.h>
#include <signal.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <sys/ipc.h>
#include <sys/sem.h>
#include <semaphore.h>
#include <sys/msg.h>
#include <sys/shm.h>
#include <sys/un.h>
typedef struct sockaddr_in addr_in_t;
typedef struct sockaddr addr_t;
typedef struct sockaddr_un addr_un_t;
int main(int argc, const char *argv[])
{
int fd = open("./jjd.txt", O_RDONLY);
//建立并打开一个新的文本文件-->jj.txt
int fd1 = open("jj.txt", O_WRONLY | O_TRUNC | O_CREAT, 0666);
while(1)
{
// 循环将文件中的内容读出写入buf数组中
char buf[16]={0};
int res = read(fd,buf,15);
if(res == 0){break;}
printf("%s",buf);
fflush(stdout);
int t = dup(STDOUT_FILENO);
dup2(fd1,STDOUT_FILENO);
printf("%s",buf);
fflush(stdout);
dup2(t,STDOUT_FILENO);
// printf("%d\n",t);
}
close(fd);
close(fd1);
return 0;
}
系统运行效果:
![](https://i-blog.csdnimg.cn/direct/2e97078b4e0344238d4acb8b1f066956.png)
第二题: 使用stat函数判断一个文件是否拥有 用户可写、同组人可写、其他组人可写权限 如果同时拥有上述3个权限,则关闭上述3个权限(使用chmod函数,自己查看man手册并使用,很简单的一个函数),如果上述3个权限有缺少,则补全权限
代码如下:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <pthread.h>
#include <semaphore.h>
#include <wait.h>
#include <signal.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <sys/ipc.h>
#include <sys/sem.h>
#include <semaphore.h>
#include <sys/msg.h>
#include <sys/shm.h>
#include <sys/un.h>
typedef struct sockaddr_in addr_in_t;
typedef struct sockaddr addr_t;
typedef struct sockaddr_un addr_un_t;
int main(int argc, const char *argv[])
{
struct stat buf = {0};
stat(argv[1],&buf);
mode_t jj = buf.st_mode;
if((jj | S_IWUSR | S_IWGRP | S_IWOTH) == jj)
{
printf("everyone has w permission");
jj = jj &~(S_IWUSR | S_IWGRP | S_IWOTH);
chmod(argv[1],jj);
}
else
{
jj = (jj | S_IWUSR | S_IWGRP | S_IWOTH);
chmod(argv[1],jj);
}
return 0;
}
系统运行结果如下:
![](https://i-blog.csdnimg.cn/direct/8092631d41a042b2bf780552e9ea7d7b.png)
二、思维导图