目录列表 C(使用 dirent 和 stat)
我正在制作一个打印目录列表应用程序 目录列表就像 Linux 和 Windows 中的“ls”和“dir”命令一样 积极地。
我的功能:打印路径指定的目录中所有文件的列表。
这是我到目前为止的代码:
#include "ls.h"
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <dirent.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <unistd.h>
// Use this function to display the files. DO NOT CHANGE IT.
void _printLine(unsigned int size, unsigned int sizeOnDisk, const char* name)
{
printf("%010u %010u %s\n", size, sizeOnDisk, name);
}
// Assume this to be the maximum length of a file name returned by readdir
#define MAX_FILE_NAME_LENGTH 255
int list(const char* path)
{
(void) path;
struct dirent *dent;
struct stat s;
DIR *dir;
dir = opendir(".");
if (!dir){
perror("opendir");
return -1;
}
errno = 0;
while ((dent = readdir(dir)) != NULL){
_printLine(s.st_size, s.st_blocks*512, dent->d_name);
}
closedir(dir);
return 0;
}
我试图将文件的“大小”和“磁盘上的大小”传递给打印函数(使用 stat),同时还传递文件的名称(使用 dirent)。但我不知道如何实现这一权利,或者是否可能?
Im making a directory listing application that prints a
directory listing just like the ’ls’ and ’dir’ commands in Linux and Windows respec-
tively.
my function: prints a listing of all files in the directory specified by path.
this is my code so far:
#include "ls.h"
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <dirent.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <unistd.h>
// Use this function to display the files. DO NOT CHANGE IT.
void _printLine(unsigned int size, unsigned int sizeOnDisk, const char* name)
{
printf("%010u %010u %s\n", size, sizeOnDisk, name);
}
// Assume this to be the maximum length of a file name returned by readdir
#define MAX_FILE_NAME_LENGTH 255
int list(const char* path)
{
(void) path;
struct dirent *dent;
struct stat s;
DIR *dir;
dir = opendir(".");
if (!dir){
perror("opendir");
return -1;
}
errno = 0;
while ((dent = readdir(dir)) != NULL){
_printLine(s.st_size, s.st_blocks*512, dent->d_name);
}
closedir(dir);
return 0;
}
Im trying to pass the "size" of the file and "size on disk" to the print function(using stat), while also passing the name of the file (using dirent). But i can't figure out how to implement this right, or if it is even possible?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您从未调用过
stat
?还缺少错误检查,但我认为缺少的调用会让您继续前进。
You never called
stat
?There is also missing error checking, but I think the missing call will get you going.