当文件作为指向数组的指针读入时,如何打印文件名?

How would you print the name of a file when it's read in as a pointer to an array?

所以,在这个程序中,我需要打印用户在 运行 程序 ./tstats input.txt 时指定的文件名。我的问题是当我尝试打印出指针指向的内容时,我得到了这个:84 18 407 ffbff2a4。现在我确切地知道前 3 组数字是什么,但是我知道的地址必须与指针有关。我知道我的打印格式需要采用字符串格式,但是您不能以字符串格式打印指针。所以这是我的问题,你如何使用我现在拥有的代码和我指向 input_from_args src 的指针打印出文件名?

#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>


enum state
{
    START,
    WORD,
    DELIM,
};

FILE*
input_from_args(int argc, const char *argv[])
{
    if (argc == 1) {
        return stdin;
    }
    else {
        return fopen(argv[1], "r");
    }
}

void
wcount(FILE *src, FILE *dest)
{
    int ch, wc, lc, cc;
    enum state cstate;

    wc = lc = cc = 0;
    cstate = START;
    while ((ch = fgetc(src)) != EOF){
        cc++;
        switch (cstate) {
            case START:
                if (isspace(ch)) {
                    cstate = DELIM;
                    if (ch == '\n') {
                        lc++;
                    }
                }
                else {
                    cstate = WORD;
                    wc++;
                }
                break;
            case DELIM:
                if (ch == '\n') {
                    lc++;
                }
                else if (!isspace(ch)) {
                    cstate = WORD;
                    wc++;
                }
                break;
            case WORD:
                if (isspace(ch)) {
                    cstate = DELIM;
                    if (ch == '\n') {
                        lc++;
                    }
                }
                break;
        }
    }

    fprintf(dest, "%4d\t%4d\t%4d\t%10p\n", wc, lc, cc, &src);
}
int
main(int argc, const char *argv[])
{
    FILE *src = input_from_args(argc, argv);
    FILE *dest = stdout;

    if (src == NULL) {
        fprintf(stderr, "%s: unable to open %s\n", argv[0], argv[1]);
        exit(EXIT_FAILURE);
    }

    wcount(src, dest);
    fclose(src);

    return EXIT_SUCCESS;
}

编辑问题 2 代码:

int
main(int argc, char* argv[])
{
 int i; 
 FILE *src = input_from_args(argc, argv);
 FILE *dest = stdout;
 
 
 for (i = 1; i < argc; i++)
 {
  if ((src = fopen(argv[i], "r")) == NULL)
  {
   fprintf(stderr, "%s: unable to open %s\n", argv[0], argv[i]); 
  }
  
  wcount(src, dest, get_filename_from_args(argc, argv[i]));
  fclose(src);
 }
 return EXIT_SUCCESS;
}

我的建议:

创建一个函数,returns 要打印的文件名 wcount:

char* get_filename_from_args(int argc, char* argv[])
{
    static char stdin_name[] = "-";
    if (argc == 1) {
        return stdin_name;
    }
    else {
        return argv[1];
    }
}

更改wcount的签名:

void wcount(FILE *src, FILE *dest, char* src_filename)

将调用更改为 wcount:

wcount(src, dest, get_filename_from_args(argc, argv));

更改 wcount 中写明详细信息的行的实现:

fprintf(dest, "%4d\t%4d\t%4d\t%s\n", wc, lc, cc, src_filename);