1
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.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>
int main(int argc, const char *argv[])
{
//使用 dup2 实现错误日志功能
int log = open("./err.txt",O_WRONLY | O_CREAT | O_APPEND,0666);
if(log == -1)
{
perror("open");
return 1;
}
int save_stderr = dup(2); //保存sdterr
int fp_open = dup2(log,2); //重定向stderr
if (fp_open == -1)
{
perror("dup2");
return 1;
}
close(log);
//使用 write 和 read 实现文件的拷贝功能
int rfd = open(argv[1],O_RDONLY);
if(rfd == -1)
{
perror("rfd");
return 1;
}
int wfd = open(argv[2],O_WRONLY | O_CREAT | O_TRUNC,0666);
if(wfd == -1)
{
perror("wfd");
return 1;
}
char buf[128] = {0};
while(1)
{
int retval = read(rfd,buf,128);
if (retval == 0)
{
break;
}
write(wfd,buf,retval);
}
close(rfd);
close(wfd);
return 0;
}
2
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.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>
//判断一个文件是否拥有用户可写权限,如果拥有,则去除用户可写权限,如果不拥有,则加上用户可写权限
int main(int argc, const char *argv[])
{
// 判断一个文件是否拥有用户可写权限
struct stat buf = {0};
stat(argv[1],&buf);//获取argv[1]文件的属性,并将属性保存到buf里面去
mode_t mode = buf.st_mode;
mode_t new_mode ; //用于修改写权限
// 判断依据为:如果一个变量里面,某个bit是1的话,|该bit为的1话,该变量是不变的
if((mode | S_IWUSR) == mode)
{
printf("%s文件拥有用户可写权限\n",argv[1]);
new_mode = mode & ~(S_IWUSR); //用于去除写权限
}
else
{
new_mode = mode | S_IWUSR; //用于添加写权限
}
int a = chmod(argv[1],new_mode); //修改权限
if (a==-1)
{
perror("chmod");
return 1;
}
//在终端显示当前文件的权限信息
if (system("ls -l") == -1)
{
perror("system");
return 1;
}
return 0;
}