Logo

Programming-Idioms

Create the list x containing the contents of the directory d.

x may contain files and subfolders.
No recursive subfolder listing.
New implementation

Be concise.

Be useful.

All contributions dictatorially edited by webmasters to match personal tastes.

Please do not paste any copyright violating material.

Please try to avoid dependencies to third-party libraries and frameworks.

Other implementations
#include <dirent.h>
struct dirent ** x = NULL;
int n = scandir (p, &x, NULL, alphasort);
(def x ((comp file-seq clojure.java.io/file) d))
#include <filesystem>
#include <ranges>
#include <iostream>
#include <vector>
auto directory_contents(auto path) {
  auto iterator = std::filesystem::directory_iterator(path);
  return std::vector<std::filesystem::path>(
    std::ranges::begin(iterator),
    std::ranges::end(iterator)
  );
}

auto main(int argc, char** argv) -> int {
  auto path = argc >= 2
    ? std::filesystem::path(argv[1])
    : std::filesystem::current_path();

  for (auto entry : directory_contents(path)) {
    std::cout << entry.string() << std::endl;
  }
}
using System.IO
var files = Directory.GetFiles(dirPath);
import std.file;
auto x = dirEntries(d, SpanMode.shallow);
import 'dart:io';
var x = Directory(d).listSync();
import "os"
x, err := os.ReadDir(d)
import System.Directory (listDirectory)
do
  x <- listDirectory d
  -- do something with x
const fs = require('fs');
const x = fs.readdirSync(d)
import java.util.ArrayList;
import java.util.Arrays;
ArrayList<File> x = (ArrayList<File>) Arrays.asList(new File(d).listFiles());
import java.io.File;
final File directory = new File(d);
final File[] x = directory.listFiles();
$x = scandir($d);
uses SysUtils, Classes;
if FindFirst(IncludeTrailingPathDelimiter(d) + '*', 
               faAnyFile and (not faDirectory), SR) = 0 then
repeat
  x.Add(SR.Name);
until FindNext(SR) <> 0;
FindClose(SR);
uses FileUtil;
x := FindAllFiles(d, '*', False);
use File::Basename;
my @x = map {basename $_} glob("$d/*");
opendir my $dh, $d or die "Could not open $d for reading: $!\n";
@x = readdir $dh;
closedir $dh;
import os
x = os.listdir(d)
x = Dir.children(d)
let x = std::fs::read_dir(d)?.collect::<Result<Vec<_>, _>>()?;
let x = std::fs::read_dir(d).unwrap();