C语言 工具型API -----------popen()

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/wait.h>
int main(int argc, char const *argv[])
{
    FILE *fb = popen("find  ../ -name '*.bmp' -o -name '*.png' -o -name '.jbg' ", "r");
    char buf[100];
    char data[5000][1024];
    char path1[200];
    char path2[] = {"./"};
    int i=0;
    while (1)
    {
        memset(buf, 0, sizeof(buf));
        fgets(buf, 100, fb);
        if (feof(fb))
        {
            perror("fgets");
            break;
        }
        if (strstr(buf, ".bmp") || strstr(buf, ".jbg") || strstr(buf, ".png"))
        {
            buf[strlen(buf)-1]='\0';
            strcpy(data[i], buf);
            i++;
            sprintf(path1, "cp %s %s", buf, path2);
            printf("path1=%s\n", path1);
            system(path1);
        }
       
        
    }
    return 0;
}

这段代码是用shell命令查找指定目录下的图片文件,并将其复制到指定目录下。

以下还一段百度的代码可供参考阅读。

#include<stdio.h>
#define _LINE_LENGTH 300
int main(void) 
{
    FILE *file;
    char line[_LINE_LENGTH];
    file = popen("ls", "r");
    if (NULL != file)
    {
        while (fgets(line, _LINE_LENGTH, file) != NULL)
        {
            printf("line=%s\n", line);
        }
    }
    else
    {
        return 1;
    }
    pclose(file);
    return 0;
}

POPEN(3)

NAME

popen, pclose - pipe stream to or from a process

SYNOPSIS

#include <stdio.h>

函数原型

FILE *popen(const char *command, const char *type);

int pclose(FILE *stream);

功能

创建一个新进程并加载一个新进程,背后原理是,先用fork()创建一个新的进程,同时调用exec函数族重新加载程序运行shell命令。popen() 函数通过创建一个管道,调用 fork 产生一个子进程,执行一个 shell运行命令来开启一个进程。这个进程必须由 pclose() 函数关闭,而不是 fclose() 函数。pclose() 函数关闭标准 I/O 流,等待命令执行结束,然后返回 shell 的终止状态。如果 shell 不能被执行,则 pclose() 返回的终止状态与 shell 已执行 exit 一样。次函数功能与system()有着异曲同工之妙,但多了一个可以直接读取其获取的输出信息。

参数

type 参数只能是读或者写中的一种,得到的返回值(标准 I/O 流)也具有和 type 相应的只读或只写类型。如果 type 是 "r" 则文件指针连接到 command 的标准输出;如果 type 是 "w" 则文件指针连接到 command 的标准输入。

command 参数是一个指向以 NULL 结束的 shell 命令字符串的指针。这行命令将被传到 bin/sh 并使用-c 标志,shell 将执行这个命令。

成功返回值

popen 的返回值是个标准 I/O 流,标准I/O流中的数据是shell程序运行的标准输出的数据,可用标准I/O读取。

失败返回值

popen 没有为内存分配失败设置 errno 值。

如果调用 fork() 或 pipe() 时出现错误,errno 被设为相应的错误类型。

如果 type 参数不合法,errno将返回EINVAL。

如果调用 fork() 或 pipe() 失败,或者不能分配内存将返回NULL;

相关推荐
被程序耽误的胡先生4 分钟前
java中 kafka简单应用
java·开发语言·kafka
刀客1234 分钟前
python小项目编程-中级(1、图像处理)
开发语言·图像处理·python
卷卷的小趴菜学编程9 分钟前
c++之多态
c语言·开发语言·c++·面试·visual studio code
冷琴199629 分钟前
基于Python+Vue开发的反诈视频宣传管理系统源代码
开发语言·vue.js·python
夏末秋也凉29 分钟前
力扣-回溯-491 非递减子序列
数据结构·算法·leetcode
penguin_bark31 分钟前
三、动规_子数组系列
算法·leetcode
楠枬37 分钟前
网页五子棋——对战后端
java·开发语言·spring boot·websocket·spring
kyle~39 分钟前
thread---基本使用和常见错误
开发语言·c++·算法
曲奇是块小饼干_1 小时前
leetcode刷题记录(一百零八)——322. 零钱兑换
java·算法·leetcode·职场和发展
坚持就完事了1 小时前
Python之numpy
开发语言·python·numpy