Home > Mobile >  Take user input using getline() and pass it to a function that opens the directory using
Take user input using getline() and pass it to a function that opens the directory using

Time:10-24

When I try to pass the args to the function using scanf the program gives me the desired output

void dirr(char *arguments);
void cd(char *arguments);
void envir(char *envp);

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

  char args[200];
    printf("enter arguments: ");
    scanf("9[^\n]", args);
    printf("arg = %s\n", args); 

    dirr(args);
  
}

void dirr(char *arguments){
   printf("Files in: %s\n", arguments);
    
    DIR *d;
    struct dirent *dir;

     d = opendir(arguments);
     
     if (d) {
       while ((dir = readdir(d)) != NULL) {
         printf("%s\n", dir->d_name);
    }
    closedir(d);
  }
}

but whenever I try to use getline instead and pass it to the same void dirr(char *arguments) function, I don't get an output from the program

void dirr(char *arguments);
void cd(char *arguments);
void envir(char *envp);

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

    char *args;
    size_t bufsize = 32;
    size_t chars;

    args = (char *)malloc(bufsize * sizeof(char));
    printf("enter arguments: ");
    chars = getline(&args, &bufsize, stdin);
    printf("%zu characters were read.\n",chars);
    printf("You typed: '%s' \n",args);

    dirr(args);
  
}


So I'm stuck in trying to see if I passed the arguments to the function wrong or if I need to take any extra steps to make sure it passes

CodePudding user response:

getline() probably returns a buffer with a trailing newline, and you should add error checking on at least opendir(). Also refactored your code a bit for readability:

#define _POSIX_C_SOURCE 200809L
#include <dirent.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>

void dirr(char *path) {
    DIR *d = opendir(path);
    if(!d) {
        strerror(errno);
        return;
    }
    printf("Files in: %s\n", path);
    for(;;) {
        struct dirent *dir = readdir(d);
        if(!dir) break;
        printf("%s\n", dir->d_name);
    }
    closedir(d);
}

int main(void) {
    size_t n = 0;
    char *buf = NULL;
    printf("enter arguments: ");
    size_t chars = getline(&buf, &n, stdin);
    buf[strcspn(buf, "\n")] = 0;
    printf("%zu characters were read.\n", chars);
    printf("You typed: '%s'\n", buf);
    dirr(buf);
}

Example run:

mkdir 1 && touch 1/{2,3} && ./your_program && rm -fr 1
enter arguments: 1
2 characters were read.
You typed: '1'
Files in: 1
..
2
.
3
  •  Tags:  
  • c
  • Related