簡體   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