C代写:ECE222 Directory Listing

Requirement

In this assignment, each student is to write a program that provides a file listing for the given directory. The program should list the filename, file size, and time last modified for each file within the directory. The program should provide the user with the option to sort the listing based on filename, on file size, or on time last modified. The program should run once and quit (it does not loop).
The syntax (usage) for the program should be:

1
prog_name [directory] [[-s][-t]]

where –s indicates sort by file size and –t indicates sort by time last modified. These flags are optional but mutually exclusive. The directory is also optional; if it is omitted than a default directory of “.” (the current directory) should be assumed. Every possible combination of command line arguments, from the above syntax, will be tested.

Analysis

本题需要实现文件系统中,类似ls命令显示的结果。
本题较为简单,如果掌握了基本的Linux函数库用法可以事半功倍。此外需要注意的是命令行参数的处理方法。最后按照测试集显示的格式,做出准确的输出即可。

Tips

下面给出命令行参数的解析逻辑

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
intmain(int argc, char *argv[]){
int arg;
int sort_by_size = 0;
int sort_by_time = 0;
while ((arg = getopt(argc, argv, "st") != -1) {
switch (arg) {
case's':
sort_by_size = 1;
break;
case't':
sort_by_time = 1;
break;
default:
printf("bad argument: %c\n", arg);
return0;
}
}
...
}