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

#include 
#include 
#include 
#include 
#include 
#include 
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
#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

函数原型       

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;

你可能感兴趣的:(常用C语言API,c语言,算法,开发语言)