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;

相关推荐
先做个垃圾出来………14 小时前
差分数组(Difference Array)
java·数据结构·算法
向上的车轮14 小时前
基于go语言的云原生TodoList Demo 项目,验证云原生核心特性
开发语言·云原生·golang
The Chosen One98514 小时前
C++ : AVL树-详解
开发语言·c++
PH_modest14 小时前
【Qt跬步积累】—— 初识Qt
开发语言·qt
hansang_IR14 小时前
【题解】洛谷 P4286 [SHOI2008] 安全的航线 [递归分治]
c++·数学·算法·dfs·题解·向量·点积
乐迪信息14 小时前
乐迪信息:AI摄像机在智慧煤矿人员安全与行为识别中的技术应用
大数据·人工智能·算法·安全·视觉检测
GanGuaGua15 小时前
Linux系统:线程的互斥和安全
linux·运维·服务器·c语言·c++·安全
怀旧,15 小时前
【C++】18. 红⿊树实现
开发语言·c++
多恩Stone15 小时前
【3DV 进阶-2】Hunyuan3D2.1 训练代码详细理解下-数据读取流程
人工智能·python·算法·3d·aigc
xiaopengbc15 小时前
在 Python 中实现观察者模式的具体步骤是什么?
开发语言·python·观察者模式