【问题标题】:could not stat file - c无法统计文件 - c
【发布时间】:2020-05-30 22:41:04
【问题描述】:

我需要统计一个文件来获取它的大小。我还需要提供文件名作为命令行参数。这是我的代码:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>

int main (int argc, char* argv[])
{
    int N = 300;
    int L = 1000;
    char Nseq[N][L];

    FILE *myfile;
    char *token;
    const char s[2] = ",";
    char *line;
    int lenline;
    char filename[100];
    strcpy(filename, "/path/");
    char name[100];
    strcpy(name, argv[1]);
    strcat(filename, name);
    strcat(filename, ".txt");
    printf("%s\n", filename);

    int err;
    struct stat st;
    int n = 0;

    err = stat(filename,&st);
    if (err < 0) {
        printf("could not stat file %s", filename);
        exit(1);
    }
    lenline = st.st_size + 1;

    line = malloc(lenline);

    myfile = fopen(filename, "r");
    if (myfile == NULL) {
        printf("could not open file %s", filename);
        exit(1);
    }

    while (fgets(line, lenline, myfile) != NULL) {
        token = strtok(line, s);
        while (token != NULL && n<N) {
            strcpy(Nseq[n], token);
            printf("%s\t%u\n", token, n);
            token = strtok(NULL, s);
            n++;
        }
    }

    fclose(myfile);

    return 0;
}

我得到的输出是:

/path/file.txt

could not stat file /path/file.txt

有人知道为什么会这样吗? 我该如何解决? 谢谢!

【问题讨论】:

  • 请考虑将您的代码示例缩减到显示您的问题所需的最低限度; “无法统计”消息之后的所有内容都是不必要的,而且主要是分散注意力。尽量减少。但是你知道这个文件确实存在吗?
  • 在错误路径中调用perror获取更详细的错误信息。 /path 是一条不寻常的路径。你确定它真的存在吗?
  • 在你的 shell 中执行ls -l /path/file.txt。它显示了什么?
  • I also need to provide the name of the file as a command line argument. - 如果目标是(表面上)在命令行上提供此信息,为什么要在前面加上 /path,然后再附加 .txt

标签: c stat


【解决方案1】:

stat (2) 的手册页说:成功时,返回零 (0)。出错时返回-1,并适当设置errno

您实际上并没有使用errno 并且基本上导致您自己的错误消息成为“出了问题”的一个相当无用的变体。

实际使用errno,通过调用隐式调用

perror("stat");

或显式调用

fprintf(stderr, "could not stat file %s: %s", filename, strerror(errno));

【讨论】:

    【解决方案2】:

    潜在的问题很可能是您在前面加上/path.txt,而在调用stat 之前,您正在构建的路径中没有实际文件。如果你只关注成功stating 文件,试试这个:

    #include <stdio.h>
    #include <string.h>
    #include <errno.h>
    #include <sys/stat.h>
    
    int main (int argc, char** argv) {
      const char* filename = argv[1];
    
      printf("Calling stat(%s)...", filename);
    
      int err;
      struct stat st;
    
      err = stat(filename, &st);
      if (err < 0) {
        printf("failed with error %d (%s)\n", err, strerror(errno));
        return err;
      } else {
        printf("succeeded\n");
        return 0;
      }
    }
    

    至少你会明白为什么stat 会失败,这将有助于说明你的代码为什么不能正常工作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-05-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多