How to modify a C program to turn it into a function

1.3k views Asked by At

I'm trying to take a given program and turn it into a function (so that i can modify it for a recursive call). The original assignment is for a directory traversal (depth-first). This is just to help me get started.

Original Program:

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

int main(int argc, char *argv[]) {
   struct dirent *direntp;
   DIR *dirp;

   if (argc != 2) {
      fprintf(stderr, "Usage: %s directory_name\n", argv[0]);
      return 1; 
   }   

   if ((dirp = opendir(argv[1])) == NULL) {
      perror ("Failed to open directory");
      return 1;
   }   

   while ((direntp = readdir(dirp)) != NULL)
      printf("%s\n", direntp->d_name);

   while ((closedir(dirp) == -1) && (errno == EINTR)) ;

   return 0;
}

This program works perfectly. But when i turn it into a function, i'm getting an error. I believe it has to do with passing the

char *argv[]

Here's the code i tried to make so far, main.c:

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

int shownames(char *argv[]);

int main(int argc, char *argv[]) {
    struct dirent *direntp;
    DIR *dirp;

    if (argc !=2) {
        fprintf(stderr, "Usage: %s directory_name\n", argv[0]);
        return 1;
    }

    shownames(*argv[]);

    return 0;
}

and shownames.c:

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

int shownames(char *argv[]) {
    struct dirent *direntp;
    DIR *dirp;

    if ((dirp = opendir(argv[1])) == NULL) {
        perror ("Failed to open directory");
        return 1;
    }

    while ((direntp = readdir (dirp)) != NULL)
        printf("%s\n", direntp->d_name);

    while ((closedir(dirp) == -1) && (errno == EINTR)) ;

    return 0;
}

I know its probably a fairly easy mistake, i just can't seem to figure out what i'm doing wrong. Any help would greatly appreciated. Thanks!

1

There are 1 answers

0
Michael On BEST ANSWER

Are you getting a compiler error? because as mbratch says, shownames(*argv[]); isn't valid syntax; specifically, empty square braces [] are for declaring an array of unknown length, not for using the array. try just:

shownames( argv );

also, you are ignoring the return value of shownames. you might want to end with:

return shownames( argv );