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;

相关推荐
罗西的思考7 分钟前
【Agent】MemOS 源码笔记---(5)---记忆分类
人工智能·深度学习·算法
生骨大头菜1 小时前
使用python实现相似图片搜索功能,并接入springcloud
开发语言·python·spring cloud·微服务
绝不收费—免费看不了了联系我1 小时前
Fastapi的单进程响应问题 和 解决方法
开发语言·后端·python·fastapi
消失的旧时光-19431 小时前
深入理解 Java 线程池(二):ThreadPoolExecutor 执行流程 + 运行状态 + ctl 原理全解析
java·开发语言
咖啡续命又一天1 小时前
Trae CN IDE 中 Python 开发的具体流程和配置总结
开发语言·ide·python·ai编程
4311媒体网1 小时前
帝国cms调用文章内容 二开基本操作
java·开发语言·php
GSDjisidi2 小时前
东京IT软件会社-(株)GSD|多种技术栈募集,高度人才+20分
开发语言·面试·职场和发展
程序员zgh2 小时前
Linux系统常用命令集合
linux·运维·服务器·c语言·开发语言·c++
獭.獭.3 小时前
C++ -- STL【unordered_set与unordered_map的实现】
开发语言·c++·unordered_map·unordered_set
Bigan(安)3 小时前
【奶茶Beta专项】【LVGL9.4源码分析】09-core-obj_class对象类系统
linux·c语言·mcu·arm·unix