简体   繁体   中英

How to Get list of all file under the directory by type in C

I have to simulate the ls function of unix in C .

I have to create a program to "Get all files under any directory by type in C".

I googled and found programs which get lists of files, but they are alphabetically sorted; I want sorted by type of file. Please, can anyone help me?

You must store the files somewhere in memory. Since this looks like a school project, I'd suggest to load the file names into a linked list, and employ one of the algorithms for sorting linked lists. This might well be the purpose of the exercise itself.

For file type let's assume "extension", ie, a .MP3 is type "Fraunhofer MPEG Layer 3" even if somebody might have renamed a .WMA file and called it .MP3. To detect "true" file type you'd need to employ something called a "magic file", and there is a libmagic out there, but is it worth it? (If it is a doctorate thesis or a commercial program the answer is 'hell yes'. If the program is to be graded by your average professor, then you judge whether to risk being considered 'too clever').

The linked list entry ought to be a struct containing the file name and a pointer to its extension; this last you can find by considering that the extension is "whatever follows the last dot in the file name", so you can leverage the strrchr function. Remember that some files will have no extension.

You judge whether to employ a memory-saving hack such as storing the pointer to the extension, or duplicating the extension with strdup . The former is faster and leaner, but you must remember that the first struct pointer (filename) MUST be freed, and the second ABSOLUTELY MUSTN'T. Having two pointers behave differently might be considered bad coding practice (it is) or a clever hack (it is), depending on whether you value maintenance time or speed/memory.

As for the retrieval of file names itself, there's no all-portable way, so this has led to the development of libraries such as Boost. But for a school project, maybe you could restrict to POSIX systems and use opendir , readdir , closedir and stat .

A good practice and a wise thing to do would be to separate the operations (directory retrieval, list sorting, list display) in different functions, so that you can test them separately and incrementally (eg: the folder retrieval does retrieve everything and you can display the files in unsorted order, etc.).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM