首页 > 解决方案 > 无法统计文件 - c

问题描述

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

#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

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

标签: cstat

解决方案


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

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

实际使用errno, 隐式调用

perror("stat");

或通过调用显式

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

推荐阅读