繁体   English   中英

这段代码模拟了ls | cat -n命令,但是我需要通过stdin而不是“。”来传输所需的目录,我该怎么办?

[英]This code emulates command ls|cat -n, but i need to transmit the needed directory through stdin instead of “.”, how can i do it?

#include <stdio.h>
#include <dirent.h>

int main() {

    struct dirent *de;

    DIR *dr;
    int i = 1;

    dr = opendir("."); // need to get directory through stdin insted of this 

    if (dr == NULL) printf("Could not open directory");

    while (((de = readdir(dr)) != NULL))
    {
        printf("\t%d. %s\n", i, de -> d_name);
        i++;
    }

    closedir(dr);
    return 0;
}

您可以从stdin中读取它,并代替"." 这是完整的例子

#include <errno.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <dirent.h>

int main(){

        struct dirent *de;
        char dirbuf[BUFSIZ] = {0};
        DIR *dr;
        int i = 1;

        puts("Chose the directory: ");
        if (fgets(dirbuf, BUFSIZ, stdin) == NULL) {
                perror("fgets");
                exit(-1);
        }
        dirbuf[strlen(dirbuf)-1] = '\0'; // remove \n

        dr = opendir(dirbuf); // need to get directory through stdin insted of this 

        if (dr == NULL) {
                perror("opendir");
                exit(-1);
        }

        while(((de = readdir(dr)) != NULL))
        {

                printf("\t%d. %s\n", i, de -> d_name);
                i++;
        }

        closedir(dr);

        return 0;

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM