Problem of the Day
A new programming or logic puzzle every Mon-Fri

Directory Listing

Welcome back to another awesome Monday!

We'll start the week off with a simple one. Today's problem is to create a program that takes in a directory on your computer and outputs the files and folders in that directory. Bonus points for differentiating between files and folders in your output.

Permalink: http://problemotd.com/problem/directory-listing/

Comments:

  • Daniel - 10 years, 10 months ago

        static void GetFilesAndSubDirs(string strPath)
        {
            System.IO.DirectoryInfo objDirInfo = new System.IO.DirectoryInfo(strPath);
            System.IO.FileInfo[] aryFiles = null;
            System.IO.DirectoryInfo[] arySubDirs = null;
            aryFiles = objDirInfo.GetFiles();
            if (aryFiles != null)
            {
                foreach (System.IO.FileInfo objFile in aryFiles)
                {
                    Console.WriteLine(String.Format("File: {0}", objFile.FullName));
                }
                arySubDirs = objDirInfo.GetDirectories();
                foreach (System.IO.DirectoryInfo objSubDirInfo in arySubDirs)
                {
                    Console.WriteLine(String.Format("Directory: {0}", objSubDirInfo.FullName));
                    GetFilesAndSubDirs(objSubDirInfo.FullName);
                }
            }
        }
    

    reply permalink

  • Anonymous - 10 years, 10 months ago

    #python 2.7
    import os
    
    for dirname, dirnames, filenames in os.walk('.'):
        # print path to all subdirectories first.
        for subdirname in dirnames:
            print "<Dir> \t" + os.path.join(dirname, subdirname) 
    
        # print path to all filenames.
        for filename in filenames:
            print "<File> \t" + os.path.join(dirname, filename)
    

    reply permalink

Content curated by @MaxBurstein