修改目录里面的.jpg结尾的文件改为.png (pid system fgets fork)

来源:互联网 发布:我想在淘宝上做代理商 编辑:程序博客网 时间:2024/04/30 09:46
/*
将改目录里面的.jpg结尾的文件改为.png
调用mv实现
不使用opendir

*/


#include <stdio.h>#include <fcntl.h>#include <unistd.h>#include <stdlib.h>#include <string.h>#include <sys/wait.h>int main(void){pid_t pid;int fd[2];char buf[1024];FILE *fp;pipe(fd);pid = fork();if(pid == 0){     //son writeclose(fd[0]);dup2(fd[1], STDOUT_FILENO);execlp("ls", "ls", NULL);}else{close(fd[1]); //parent readchar *s;fp = fdopen(fd[0], "r");while(fgets(buf, 1024, fp)){if( (s = strstr(buf, ".jpg")) ){*s = '\0';printf("%s.png\n", buf);}}wait(NULL);}return 0;}

/*将改目录里面的.jpg结尾的文件改为.png 调用mv实现不使用opendir*/

#include <stdio.h>#include <fcntl.h>#include <unistd.h>#include <stdlib.h>#include <string.h>#include <sys/wait.h>int main(void){pid_t pid;int fd[2];char buf[1024];FILE *fp;pipe(fd);pid = fork();if(pid == 0)//son write{ close(fd[0]);dup2(fd[1], STDOUT_FILENO);execlp("ls", "ls", NULL);}else{close(fd[1]); //parent readchar *s;fp = fdopen(fd[0], "r");while(fgets(buf, 1024, fp)){if( (s = strstr(buf, ".jpg")) ){char str_mv[1024] = "mv "; //mv 1.jpg 1.pngbuf[strlen(buf) - 1] = '\0'; //fgets 会读取最后的\n,替换为\0 strcat(str_mv, buf); strcat(str_mv, " "); //mv 1.jpg 1.png 添加.jpg后面的空格*s = '\0';strcat(buf, ".png"); //buf里面为1.pngstrcat(str_mv, buf); //str_mv里面为 mv 1.jpg 1.pngprintf("%s\n", str_mv);system(str_mv); }}wait(NULL); //回收子进程}return 0;}/*$ ./a.out mv 1.jpg 1.pngmv 2.jpg 2.pngmv a.jpg a.pngmv b.jpg b.png$ ls1.png 2.png a.out a.png b.png pop_name2.c*/




0 0
原创粉丝点击