gpt4 book ai didi

c - 如何使用 'ls' cmd 仅打印目录中的隐藏文件?

转载 作者:太空宇宙 更新时间:2023-11-04 08:13:58 24 4
gpt4 key购买 nike

我正在尝试从 cmd 行读取路径,然后运行“ls”cmd 以仅打印指定路径中的隐藏文件及其长信息,然后打印到文本文件。我的问题是“ls”返回:

ls: 非法选项 --

ls: 非法选项 -- .

ls: 非法选项 -- ?

ls: 非法选项 -- *

这是我的代码:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <dirent.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>

#define NUMARG 2


/* start main */
int main(int argc, char *argv[]){

/* define data */
DIR *dirptr;
struct dirent *dp;
int pid;
int fd = open("output_file", O_WRONLY|O_CREAT, 0666);

/* Command Line Check */
if(argc != NUMARG){
fprintf(stderr, "usage: %s dirname\n", argv[0]);
exit(1);
}

/* Open the specified directory */
if((dirptr = opendir(argv[1])) == NULL){
fprintf(stderr, "Could not open directory %s\n", argv[1]);
exit(1);
}

/* fork another process */
switch(pid = fork()){

/* succesfull child process */
case 0:
dup2(fd, 1);
close(fd);
printf("Running ls\n");
execlp( "ls", "ls" , "-ld .?*", argv[1], (char*)NULL);
perror("execlp");
exit(1);
default:
sleep(5);
printf("Hitting default...\n");
break;
case -1:
perror("err");
exit(1);
}
}

最佳答案

通过 shell 运行 ls

execlp("/bin/sh", "/bin/sh", "-c", "ls -l .?*", (char *) NULL);

这样您就可以访问 shell 通配符。

关于c - 如何使用 'ls' cmd 仅打印目录中的隐藏文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36956510/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com