C编程-Stat系统调用-错误 [英] C Programming - Stat system call - Error
问题描述
我是C语言的新手,但是尝试了一些系统调用.
I'm new to C but trying some system calls.
我正在编写一个程序,它遍历目录中的所有文件并打印当前文件名和大小.我可以让程序打印文件名,但是在执行stat系统调用时出错.
I'm writing program that iterates through all files in a directory and prints the current file name and size. I can get the program to print the file name but it errors when I preform the stat system call.
下面是一些代码:
while (dptr = readdir(dirp)) {
if (stat(dptr->d_name, &buf) != 0) {
//Always does this and it does print the file name
printf("Error on when getting size of %s \n", dptr->d_name);
} else {
//Never gets here
printf("%u", buf.st_size);
}
}
我有这样描述的结构:
struct stat buf;
struct dirent *dptr;
DIR *dirp;
如果我更改:
if (stat(dptr->d_name, &buf) != 0)
到
if (stat(dptr->d_name, &buf) != [EACCES])
它仍然进入循环,这使我认为它无法读取文件名,但可以在错误语句中毫无问题地将其打印出来.
It still goes into the loop which makes me think it can't read the file name but it's printing it in the error statement without a problem.
有人可以指出我正确的方向吗?谢谢!
Can someone point me in the right direction? Thanks!
Аркадий
推荐答案
首先,如果遇到错误,则stat()返回-1,而不是实际的错误代码.错误代码将在errno中设置.打印错误的一种简单方法是使用perror().
First, stat() returns -1 if an error is encountered, not the actual error code. The error code will be set in errno. An easy way to print the error is to use perror().
第二,dptr-> d_name仅提供文件的相对文件名,而不提供完整文件名.要获取完整的文件名,必须从相对文件名和目录名生成它.
Second, dptr->d_name only provides a relative filename of the file and not the full filename. To obtain the full filename, you must generate it from the relative filename and the directory name.
这里是一个例子:
int cwdloop(void)
{
DIR * dirp;
struct stat buff;
struct dirent * dptr;
char filename[1024];
char dirname[1024];
if (!(getcwd(dirname, 1024)))
{
perror("getcwd");
return(1);
};
dirp = opendir(dirname);
if (!(dirp))
{
perror("opendir()");
return(1);
};
while ((dptr = readdir(dirp)))
{
snprintf(filename, 1024, "%s/%s", dirname, dptr->d_name);
if (stat(filename, &buff) != 0)
{
perror("stat()");
return(1);
} else {
printf("size: %u\n", (unsigned)buff.st_size);
};
};
closedir(dirp);
return(0);
}
这篇关于C编程-Stat系统调用-错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!