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;

相关推荐
偷光2 小时前
浏览器中的隐藏IDE: Elements (元素) 面板
开发语言·前端·ide·php
DKPT2 小时前
JVM栈溢出和堆溢出哪个先满?
java·开发语言·jvm·笔记·学习
胡小禾2 小时前
JDK17和JDK8的 G1
jvm·算法
胖咕噜的稞达鸭4 小时前
算法入门:专题攻克一---双指针(3)有效三角形的个数 查找总价格为目标值的两个商品(剑指offer题目)
算法
gopyer5 小时前
180课时吃透Go语言游戏后端开发6:Go语言的循环语句
开发语言·游戏·golang·循环语句
楼田莉子8 小时前
Qt开发学习——QtCreator深度介绍/程序运行/开发规范/对象树
开发语言·前端·c++·qt·学习
逻辑留白陈8 小时前
Adaboost进阶:与主流集成算法对比+工业级案例+未来方向
算法
Learn Beyond Limits8 小时前
Mean Normalization|均值归一化
人工智能·神经网络·算法·机器学习·均值算法·ai·吴恩达
天选之女wow9 小时前
【代码随想录算法训练营——Day28】贪心算法——134.加油站、135.分发糖果、860.柠檬水找零、406.根据身高重建队列
算法·leetcode·贪心算法
Gohldg9 小时前
C++算法·贪心例题讲解
c++·数学·算法·贪心算法