C 程序中 Linux 系统调用的输出 [英] Output of the Linux System Call in C program

查看:31
本文介绍了C 程序中 Linux 系统调用的输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在我的 C 程序中操作 ls -al 命令的输出.有办法吗?

I want to manipulate the output of the ls -al command in my C program. Is there a way to do it ?

int main()
{
    int return_value;
    return_value = system("ls -al ");
    return return_value;
}

推荐答案

你需要一个管道到进程.

You need a pipe to the process.

#include <stdio.h>
#include <stdlib.h>

int main()
{ 

  FILE *fp;
  char output[1024];

  fp = popen("/bin/ls -al", "r");
  if (fp == NULL)
    exit(1);

  while (fgets(output, 1023, fp) != NULL) 
    printf("%s", output);

  pclose(fp);

  return 0;
}

这篇关于C 程序中 Linux 系统调用的输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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