c - 无法统计文件 - 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
有谁知道为什么会这样?我该如何解决?谢谢你!
解决方案
(2)的手册页stat
说:成功时,返回零 ( 0
)。出错时-1
返回,并errno
进行适当设置。
您实际上并没有使用errno
并且基本上导致您自己的错误消息成为“出现问题”的一个相当无用的变体。
实际使用errno
, 隐式调用
perror("stat");
或通过调用显式
fprintf(stderr, "could not stat file %s: %s", filename, strerror(errno));
推荐阅读
- webpack - 仅在 webcomponent 范围内使用 webpack 捆绑的 CSS
- wpf - directx12 是否可以仅渲染到窗口的一部分?
- python - CUDA_ERROR_LAUNCH_FAILED 在训练过程中引发
- python - 3和5的倍数之和
- spring-boot - 缓存警告:尝试计算对象图的大小时达到了 1,000 个对象的配置限制
- http - 带有条件的更新的 Http 状态码
- javascript - POST后Express js MongoDB返回对象
- python - softmax_cross_entropy_with_logits 南
- php - 如何从 Table1 统计每个月的记录并将其存储在 Table2 中
- google-cloud-composer - 使用 Cloud Composer 访问存储桶时出错