简体   繁体   English

如何修改C程序以将其转换为功能

[英]How to modify a C program to turn it into a function

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: 这是到目前为止我尝试制作的代码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: 和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! 谢谢!

Are you getting a compiler error? 您收到编译器错误吗? because as mbratch says, shownames(*argv[]); 因为正如mbratch所说,shownames 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 );

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

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