如何在C / C ++中将系统调用的输出重定向到程序内部? [英] How to redirect the output of a system call to inside the program in C/C++?

查看:88
本文介绍了如何在C / C ++中将系统调用的输出重定向到程序内部?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用C ++编写程序,对Linux OS当前目录中的所有文件进行一些特殊处理。

I'm writing a program in C++ which do some special treatment for all the files in the current directory on Linux OS.

所以我在考虑使用诸如 system( ls)之类的系统调用来获取所有列表文件。

So i was thinking of using system calls such as system("ls") to get the list of all files.

但是如何将其存储在我的程序中? (如何将ls的输出重定向到我在程序中声明的字符串)

but how to store it then inside my program ? ( how to redirect the output of ls to let's say a string that i declared in the program )

谢谢

推荐答案

我建议您不要调出 ls -使用 opendir / readdir正确完成工作/ closedir 直接读取目录。

I suggest you don't call out to ls - do the job properly, using opendir/readdir/closedir to directly read the directory.

代码示例,打印目录条目:

Code example, print directory entries:

// $ gcc *.c && ./a.out 
#include <stdlib.h> // NULL
#include <stdio.h>  
#include <dirent.h>

int main(int argc, char* argv[]) {
  const char* path = argc <= 1 ? "." : argv[1];

  DIR* d = opendir(path);
  if (d == NULL) return EXIT_FAILURE;

  for(struct dirent *de = NULL; (de = readdir(d)) != NULL; )
    printf("%s/%s\n", path, de->d_name);

  closedir(d);
  return 0;
}

这篇关于如何在C / C ++中将系统调用的输出重定向到程序内部?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆