2016-01-27 45 views
0

我试图创建一个程序,它将计算目录的数量或可读/可写/可执行文件的数量。用户只输入作者姓名和字母“d”,“r”,“w”或“x”。我试图在程序中直接调用“ls -l”,但这导致了一个错误。如何在C程序中调用UNIX命令?C - 程序中的UNIX命令

+1

看看'system()' – Haris

+1

虽然['system()'](http://pubs.opengroup.org/onlinepubs/9699919799/functions/system.html)'有效',你必须制造仔细的命令行;启动程序无法过滤输出(在正常情况下)。您可能需要使用POSIX函数['popen()'](http://pubs.opengroup.org/onlinepubs/9699919799/functions/popen.html),或者['fork()'](http:// pubs.opengroup.org/onlinepubs/9699919799/functions/fork.html)和['execvp()'](http://pubs.opengroup.org/onlinepubs/9699919799/functions/execvp.html)及相关函数(' pipe()','dup2()',...)。 –

+1

您可能还想研究POSIX函数['nftw()'](http://pubs.opengroup.org/onlinepubs/9699919799/functions/nftw.html), ['opendir()'](http:/ /pubs.opengroup.org/onlinepubs/9699919799/functions/opendir.html), ['readdir()'](http://pubs.opengroup.org/onlinepubs/9699919799/functions/readdir.html), [ 'STAT()'](http://pubs.opengroup.org/onlinepubs/9699919799/functions/stat.html)。 –

回答

1

我试着直接在我的程序中调用“ls -l”,但是这导致了错误。如何在C程序中调用UNIX命令?

您可以在SE C程序system,例如:

system("ls -l"); 

对于工作,你还需要#include <stdlib.h>

+0

我认为在这种情况下程序输出也是必要的。 –

+0

在这种情况下,使用'popen' – immibis

0

使用find命令可能会更好地工作,你可以使用命令“find。-td | wc -l”来计算目录,并为具有相应标志的文件执行类似操作。