[Question]
  [
## Goal:
Create a program to find the smallest file in the current folder.
* File size may be measured in bytes or characters.
* If multiple files have the same size, you can either choose one or display all of them.
* You can assume there will be at least one file in the folder, and no files will have a size of 0.
* Assume that all files in the folder can be loaded by the language you're using.
* ### Assume that there are no folders in the current directory.
### Input:
The program should not take any input from the user, unless:
* If your language doesn't have a "current folder", it may ask the user for a folder name/path.
* If your language cannot directly access files on your computer, it may allow the user to upload files. (JavaScript, for example)
### Output:
The name of the smallest file should be displayed.
* Leading/trailing symbols are allowed, as long as it's clear which file has been chosen.
* (Printing a list of all the files is against the rules).
### Notes:
* [Standard Loopholes](http://meta.codegolf.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default "Standard Loopholes") are not allowed.
* You cannot modify/create/delete files in the folder to change the result.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"); shortest answer (in bytes) wins.
  
[Answer]
# Bash + coreutils, 13 bytes
```
ls -Sar|sed q
```
Explanation:
```
ls -Sar|sed q
ls            # list files
   -S         # sorted, biggest first
     a        # show hidden files
      r       # reversed (smallest first)
       |sed q # q is quit at first line that matches given regex, 
              # given regex is empty so guaranteed match.         
```
[Answer]
## Python ~~2~~ 3, ~~94~~ ~~76~~ ~~74~~ 54 bytes
-18 bytes thanks to @orlp  
-2 bytes thanks to @Jonathan Allan  
-20 bytes thanks to a change in challenge specs
```
from os import*
print(min(listdir(),key=path.getsize))
```
[Answer]
# [PowerShell](https://github.com/PowerShell/PowerShell), ~~30~~ ~~24~~ 21 bytes
```
(ls|sort le*)[0].Name
```
[Try it online!](https://tio.run/nexus/powershell#@6@RU1xTnF9UopCTqqUZbRCr55eYm/r/PwA "PowerShell – TIO Nexus")
`ls` is an alias for `Get-ChildItem`. That's piped to `sort-object` with the `length` attribute, so the files are sorted by size. We index into that with the `(...)[0]` to get the first (i.e., smallest), and then take the `.Name` thereof. Output via implicit `Write-Output` happens at program completion.
*Saved 6 bytes since we're guaranteed that only files exist in the directory. Saved an additional 3 thanks to ConnorLSW.*
[Answer]
# Vim 12 bytes
```
!!ls -Sa
Gd{
```
[Try it online!](https://tio.run/nexus/v#@6@omFOsoBucyOWeUv3/PwA "V – TIO Nexus")
## Explanation:
`!!` is the *filter* command. It pipes the contents of the current line to an arbitrary system command, and sends the output back into the buffer. It's useful for using external tools for things that bash is better at than vim, for example `!!rev` to reverse the current line, or `!Gxxd` to hexdump the buffer. In our case, the buffer is empty so it's equivalent to `:r!ls`, which just feeds the output of the command into the current line.
Now the cursor is on line 1, and we want to delete every line but the last one. The naïve approach is
```
G       " Go to the last line
 k      " Go up one line
  d     " Delete:
   gg   "   Everything up to the first line
```
But we can do better. Like I explained in [this tip](https://codegolf.stackexchange.com/a/103946/31716), the `{` can *usually* (but not always) be equivalent to `gg`. Here, it's even better. Because the motion is *character-based*, not *line-based* like `gg` is, we don't have to go up a line first, leaving us with
```
Gd{
```
[Answer]
# Java 7, ~~149~~ 142 bytes
```
String f(){String n="";long s=-1>>>1,p;for(java.io.File f:new java.io.File(".").listFiles())if((p=f.length())<s){n=f.getName();s=p;}return n;}
```
[Try it online!](https://tio.run/nexus/java-openjdk#TY8xbsMwDEX3nILwRAGpgKxR5bFbu2QsMiip5KiQJUGkUwSGz@7SSIdO/HwEicdrckTw7mKGeT1xi3mAgGr@i9l2nUlFEtmXQ9/3h301oTT8dnenY9FvMXkIx@x/4D/CTndKp0i8dYRKxYBYbdDJ54FvAl5JzVnA4PnDjR6VIVvN0jxPLUM2y1qnS4pXIHYs5V7iF4wiik@3z7Nrg4J5B099BxY2ja2RY4JPD2I/6jKxrrLBKaPT8pwMl92y/gI "Java (OpenJDK) – TIO Nexus")
-7 bytes thanks to CAD97
[Answer]
## Ruby, ~~61~~ ~~40~~ ~~38~~ 37 bytes
Thanks G B and Value Ink
```
p Dir[?*,".*"].min_by{|x|File.size x}
```
[Answer]
# Mathematica, 35 bytes
```
FileNames[]~MinimalBy~FileByteCount
```
`FileNames[]` produces a list of names of all the files (and directories) in the current directory; `~MinimalBy~FileByteCount` selects the name of the file whose byte count is smallest. `FileByteCount` throws a bunch of errors when it's applied to directories, but the errors don't derail the program.
[Answer]
## SH (Linux/Unix) ~~15~~ ~~14~~ ~~13~~ 14 bytes
```
ls -aS|tail -1
```
`-S` sorts by size (descending),
~~`-r`reverses~~ and `tail -1` outputs the last file in the list.
@ Dennis Thanks for saving 1 byte
@Dani\_l Thanks for saving 1 byte.
[Answer]
# MATLAB / Octave, ~~52~~ 48 bytes
```
d=dir;[~,n]=min([d.bytes]./~[d.isdir]);d(n).name
```
**Explanation**
This gets a directory listing of all files and folders in the current directory using `dir`. The output of `dir` is a `struct` containing the filename, whether it's a directory or not, the size (in bytes), etc.
We can then take an array of the sizes of each in bytes `[d.bytes]` and perform element-wise division with a boolean indicating whether it's a directory or not `~[d.isdir]` which will yield `Inf` where it's a directory (division by zero) and the size in bytes otherwise (division by 1).
We find the index of the minimum of this array using the second output of `min` and use that to index into the initial struct and display the name with `d(n).name`
[Answer]
**Scala, 52 bytes**
Old version, 79 bytes
```
new java.io.File(".").listFiles.map(a=>a.getName->a.length)sortBy(_._2)apply(0)
```
Adjusted according to jaxad0127's advice. It is only 52 bytes now.
```
new java.io.File(".").listFiles.sortBy(_.length)head
```
[Answer]
## Batch, ~~43~~ ~~39~~ 35 bytes
```
@dir/b/os|(set/pf=&call echo %%f%%)
```
Output includes a leading space for some reason, but fortunately that's allowed. Edit: Now assuming there are no directories to save 4 bytes.
[Answer]
# [Perl 6](https://perl6.org), ~~33 32 31~~ 16 bytes
```
'.'.IO.dir.grep(*.f).min(*.s).put
```
[Try it](https://tio.run/nexus/perl6#@6@up67n6a@Xklmkl16UWqChpZemqZebmQdkFGvqFZSW/P8PAA "Perl 6 – TIO Nexus")
```
put '.'.IO.dir.min:{try .s//Inf}
```
[Try it](https://tio.run/nexus/perl6#@19QWqKgrqeu5@mvl5JZpJebmWdVXVJUqaBXrK/vmZdW@/8/AA "Perl 6 – TIO Nexus")
```
put $*CWD.dir.min:{try .s//Inf}
```
[Try it](https://tio.run/nexus/perl6#@19QWqKgouUc7qKXklmkl5uZZ1VdUlSpoFesr@@Zl1b7/z8A "Perl 6 – TIO Nexus")
```
put dir.min: *.s
```
[Try it](https://tio.run/nexus/perl6#@19QWqKQklmkl5uZZ6WgpVf8/z8A "Perl 6 – TIO Nexus")
## Expanded:
```
put        # print with trailing newline
dir        # the list of files in the current directory
.min:      # find the minimum by
  *.s      # calling the `s` method (size) in a Whatever lambda
```
[Answer]
# [J](http://jsoftware.com/), ~~21~~ 20 bytes
```
>{.,(/:2&{"1)1!:0'*'
```
Saved a byte thanks to @[Conor](https://codegolf.stackexchange.com/users/31957/conor-obrien).
## Explanation
```
>{.,(/:2&{"1)1!:0'*'
                 '*' Glob all files in current directory
             1!:0    Table of file metadata in that directory
       2&{"1         Get the file size of each
     /:              Sort the files by that
   ,                 Flatten
 {.                  Get the first value
>                    Unbox
```
[Answer]
## PHP, ~~84~~ 62 bytes
```
$t=array_map(filesize,$g=glob('*'));asort($t);echo$g[key($t)];
```
Since the question was updated with the assumption that there will be no folders in the current directory, I was able to remove the file check stuff and golf this down.
---
**Here is my old answer:**
```
$t=array_map(filesize,$g=array_filter(glob('*'),is_file));asort($t);echo$g[key($t)];
```
This is the best I could do. Maybe there is a better way I'm missing.
```
$t=array_map(              # visit each array element and...
    filesize,              # map each filename to its filesize...
    $g=array_filter(       # using an array of...
        glob('*'),         # all files and directories...
        is_file            # filtered by files...
    )                      # 
);                         # 
asort($t);                 # sort the array of filesizes, then...
echo$g[key($t)];           # print element from the array of files using the first key of the sorted array as an index
```
[Answer]
## BATCH File, ~~77~~ ~~72~~ ~~63~~ 60 bytes
```
@FOR /F tokens^=* %%G IN ('dir/o-s/b')DO @SET[=%%G
@ECHO %[%
```
There's no direct equivalent of `head` or `tail` in BATCH, at least to my knowledge, so here's a kludgy work-around. (with much assistance from @Neil - thanks!)
The `dir` command, with `/o-s` to sort in descending file size, and `/b` to output only the file names. We loop through those with `FOR /F`, setting the variable `[` to the file name each time. Finally, we output just the last one with `ECHO %[%`.
*Saved 9 more bytes thanks to Neil and thanks to guarantees that no directories are present.*  
*Saved 3 bytes thanks to HackingAddict1337.*
[Answer]
# Node.js (using [`walk`](https://www.npmjs.com/package/walk)), 114 bytes
Ignore newline:
```
require('walk').walk(__dirname).on('file',(r,s,n)=>
(m=s.size>m.size?m:s,n()),m=0).on('end',_=>console.log(m.name))
```
This invokes a walker that traverses through the current directory (`__dirname`) and for each file calls a function with its stat `s` and a function next `n()` that must be invoked to continue the traversal. Then at the `end`, it prints a filename with the minimum `size` in bytes found. `s.size>m.size` returns `false` when `m.size` is `undefined`, so after the first callback, `m` is equal to the first file found, and continues from there normally.
[Answer]
## R, 36 bytes
```
x=file.info(y<-dir())$s;y[x==min(x)]
```
**Explained**
`file.info()` returns a `data.frame` of "file information" when given a character or character vector of file/folder names which when used on the list of files/folders in the current directory (`dir()`), looks something like:
```
                                                               size isdir mode               mtime               ctime               atime exe
Polyspace_Workspace                                               0  TRUE  777 2014-11-28 17:29:25 2014-11-28 17:29:25 2014-11-28 17:29:25  no
Python Scripts                                                    0  TRUE  777 2016-03-21 23:59:41 2016-03-21 23:59:41 2016-03-21 23:59:41  no
R                                                                 0  TRUE  777 2015-12-23 20:11:02 2015-12-23 20:11:02 2015-12-23 20:11:02  no
Rockstar Games                                                    0  TRUE  777 2015-04-14 12:23:05 2015-04-14 12:23:03 2015-04-14 12:23:05  no
TrackmaniaTurbo                                                   0  TRUE  777 2016-03-24 17:15:05 2016-03-24 13:13:48 2016-03-24 17:15:05  no
ts3_clientui-win64-1394624943-2014-06-11 03_18_47.004772.dmp 314197 FALSE  666 2014-06-11 02:18:47 2014-06-11 02:18:47 2014-06-11 02:18:47  no
```
Subsequently we just have the find the name of the file for which the `size` column (abbreviated using `$s`) is the smallest. Consequently, if there are more than one file with the smallest size, all will be returned.
Bonus: if we also wanted to disregard folders in the current directory we could simply search for size when `isdir == FALSE`: `x=file.info(y<-dir());y[x$s==min(x$s[!x$i])]` which turns out to be 44 bytes.
[Answer]
# [Tcl](http://tcl.tk/), 88 bytes
```
set s Inf
lmap f [glob -ty f *] {if [set m [file si $f]]<$s {set n $f
set s $m}}
puts $n
```
[Try it online!](https://tio.run/##dY7LCsIwEEX3@YpZdCXoF7gSpHThxm3Joo9JCEweOClVSr89JioiBXeXyzlzJw6UGCMoaH1AB2w7okO8R5ilCFNkqBSwGMgz5ijEL2xxNJPd0hcc//C90RpvW/7U1PX5@lVe7zA0TgmyXSiyJt/DPj5y3klYTK4KZKFVhhDYZE3KY8WwlN6V4feVyq7rZ8il9AQ "Tcl – Try It Online")
[Answer]
# SmileBASIC, 110 bytes
```
DIM F$[0]FILES"TXT:",F$FOR I=0TO LEN(F$)-1F$[I][0]="TXT:
S=LEN(LOAD(F$[I],0))IF!Z||S<Z THEN Z=S:B=I
NEXT?F$[B]
```
Only looks at `TXT:` files, since `DAT:` files cannot be loaded unless you already know their size, making it impossible to load a random one.
[Answer]
# [Groovy](http://groovy-lang.org/), 49 bytes
```
m={f->f.listFiles().sort{it.length()}[0].getName()}
```
[Try it online!](https://tio.run/nexus/groovy#@1@dpmuXppeTWVzilpmTWqyhqVecX1RSnVmil5Oal16SoaFZG20Qq5eeWuKXmJsK5P3/DwA "Groovy – TIO Nexus")
Closure, usage: `m(new File("location"))`
[Answer]
# C#, 277 bytes
Not the shortest, but what would you expect from C#?
## Golfed
```
using System.Linq;using static System.IO.Directory;class P{static void Main(){var x=GetFiles(GetCurrentDirectory());var d=new long[]{}.ToList();foreach(var s in x){var b=new System.IO.FileInfo(s).Length;if(!d.Contains(b))d.Add(b);}System.Console.Write(x[d.IndexOf(d.Min())]);}}
```
## Ungolfed
```
//Linq using for List.Min()
using System.Linq;
//Static using to save bytes on GetCurrentDirectory() and GetFiles()
using static System.IO.Directory;
class P
{
    static void Main()
    {
        //String array containing file paths
        var x = GetFiles(GetCurrentDirectory());
        //Creating a Long array and converting it to a list, less bytes than "new System.Collections.Generic.List<long>()"
        var d = new long[] { }.ToList();
        foreach (var s in x) //Loop through all file paths
        {
            //Getting file size in bytes
            var b = new System.IO.FileInfo(s).Length;
            if (!d.Contains(b))
                //If there isn't already a file with this size in our List, add the file path to list
                d.Add(b);
        }
        //Get index of the smallest Long in our List, which is also the index of the file path to the smallest file, then write that path
        System.Console.Write(x[d.IndexOf(d.Min())]);
    }
}
```
[Answer]
# [Röda](https://github.com/fergusq/roda "branch roda-0.12"), ~~32~~ 31 bytes
```
{ls""|sort key=fileLength|pull}
```
It's an anonymous function that sorts the files in the current directory by file length and selects then the first file with `pull`.
Use it like this: `main{ {ls""|sort key=fileLength|pull} }`
[Answer]
# [Zsh](https://www.zsh.org/) `-C4`, 9 bytes
* `-C`: enables noclobber (Zsh will not redirect to files which already exist)
* `-4`: enables globdots (`*` matches files beginning with `.`.
> 
> Leading/trailing symbols are allowed, as long as it's clear which file has been chosen.
> 
> 
> 
The following prints the file name, preceded by `$0:1: file exists:`  and followed by a newline, to stderr:
```
>*(oL[1])
```
~~[Try it online!](https://tio.run/##qyrO@J@bnZJZpFCSWlzClZwCoVOTM/IV1HPy89IV0jJzUtUV7BQSoYIQPhjYKSRhU5n8HyyooVWjp6Wpke8TbRir@f8/AA "Zsh – Try It Online")
[Try it online!](https://tio.run/##qyrO@J@bnZJZpFCSWlzClZwCoVOTM/IV1HPy89IV0jJzUtUV7BQSoYIQPhjYKSRhU5n8HyyopeGS7xNtGKv5/z8A "Zsh – Try It Online")~~
[Try it online!](https://tio.run/##qyrO@F@cWqKg62zClZudklmkUJJaXMKVnAKhU5Mz8hXUc/Lz0hXSMnNS1RXsFPQSoaIQATAAiiZhVZv8305LI98n2jBW8/9/AA "Zsh – Try It Online")
* `(oL)` sorts by size
* `[1]` selects the first match
---
I used to have just `*(oL[1])` and rely on Zsh printing "command not found", but if the file matches the name of a builtin or executable, this would break. Additionally, the previous `echo` methods would break if the smallest file was `-e` or `-` or similar (interpreted as a flag to `echo`). This new method works for all file names and is still very short.
[Answer]
# SmileBASIC 3, 105 bytes (competing?)
Beats [12Me21's answer](https://codegolf.stackexchange.com/a/108408/42096) but still suffers from inability to load DAT files (which feels very cruel to be disqualifying considering the circumstances.)
```
DIM F$[0],T[0]FILES"TXT:",F$FOR I=0TO LEN(F$)-1F$[I][0]="TXT:
PUSH T,LEN(LOAD(F$[I]))NEXT
SORT T,F$?F$[0]
```
The shorter version above is annoying and prompts you on every file to load, but it does work. For two bytes more you can suppress the prompt; change line 2 to this:
```
PUSH T,LEN(LOAD(F$[I],0))NEXT
```
[Answer]
## Batch File, 33 bytes
Batch files are moderately competitive this time, oddly enough.
```
@dir/os/b>..\q&set/pa=<..\q&"%a%.
```
**Output**
[![enter image description here](https://i.stack.imgur.com/vFLFa.png)](https://i.stack.imgur.com/vFLFa.png)
---
Find a way to stop the creation of `q` prior to `dir/os/b` being run and you'll save a maximum of 6 bytes by not needing to put the output file in a separate directory.
```
@dir/os/b>q&set/pa=<q&"%a%
```
Will always output `q` as the smallest file (unless tied for another 0 byte file) as it is created as an empty file before `dir/b/os` gathers a list of files.
[Answer]
# [C++17 (gcc)](https://gcc.gnu.org/), 180 bytes
```
#include<filesystem>
using namespace std::filesystem;auto f(){std::error_code e;path r;size_t m=-1,s;for(auto&p:directory_iterator(".")){s=file_size(p,e);if(s<m)m=s,r=p;}return r;}
```
[Try it online!](https://tio.run/##RY7NasMwEITP9VOIFBqJ2IWcCpaUJykYIa9dgfXDrnRIg1@9rpRDe9pld@absSkNq7XHqwt2KzMw5SJlBONvfze1uA3oThn8rSvkwsqC8UDJWGCU53H8F0hTcmQLF4/nAxAjTjZWMMhk8hdDSe4bpsy8Hq49ySUib563NM4OweaI98llQFM3fno/iYrSLWBqRp56ENItnJQXXlOPOskdIRcMlb0fLlS0cYEL9uheniVsLJkp1Vq1cf4MZ9ntx49dNrPSMVSRtpfL9eMX "C++ (gcc) – Try It Online")
Requires a recent standard library that implements `std::filesystem`.
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell) 6+ for Windows, 20 bytes
```
ls|sort l* -t 1|% n*
```
[Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/P6e4pji/qEQhR0tBt0TBsEZVIU/r/38A "PowerShell – Try It Online")
Unrolled:
```
ls|sort length -top 1|% Name
```
See also AdmBorkBork's [answer](https://codegolf.stackexchange.com/a/108409/80745).
[Answer]
# Red, 56 bytes
```
first sort/compare read %. func[a b][(size? a)< size? b]
```
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 51 bytes
```
.ml$open(b,"rb").read()$$__import__("os").listdir()
```
I feel like Pyth might not be the best tool for the job here...
[Try it online!](https://tio.run/##DcnBCsAgCADQf4kOClu/JIuCCZViXvbzc3vXp4/fEWWOLNoX1CNZTVisXw0wZyKeKuZEkGT/MXh7YwOMeEWdZe042wc "Pyth – Try It Online")
]