【发布时间】: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?