Getting the filenames of all files in a folder
You could do it like that:
File folder = new File("your/path");
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
System.out.println("File " + listOfFiles[i].getName());
} else if (listOfFiles[i].isDirectory()) {
System.out.println("Directory " + listOfFiles[i].getName());
}
}
Do you want to only get JPEG files or all files?
Directory.GetFiles: how to get only filename, not full path?
You can use System.IO.Path.GetFileName
to do this.
E.g.,
string[] files = Directory.GetFiles(dir);
foreach(string file in files)
Console.WriteLine(Path.GetFileName(file));
While you could use FileInfo
, it is much more heavyweight than the approach you are already using (just retrieving file paths). So I would suggest you stick with GetFiles
unless you need the additional functionality of the FileInfo
class.
How can I get the list of files in a directory using C or C++?
UPDATE 2017:
In C++17 there is now an official way to list files of your file system: std::filesystem
. There is an excellent answer from Shreevardhan below with this source code:
#include <string>
#include <iostream>
#include <filesystem>
namespace fs = std::filesystem;
int main()
{
std::string path = "/path/to/directory";
for (const auto & entry : fs::directory_iterator(path))
std::cout << entry.path() << std::endl;
}
Old Answer:
In small and simple tasks I do not use boost, I use dirent.h. It is available as a standard header in UNIX, and also available for Windows via a compatibility layer created by Toni Ronkko.
DIR *dir;
struct dirent *ent;
if ((dir = opendir ("c:\\src\\")) != NULL) {
/* print all the files and directories within directory */
while ((ent = readdir (dir)) != NULL) {
printf ("%s\n", ent->d_name);
}
closedir (dir);
} else {
/* could not open directory */
perror ("");
return EXIT_FAILURE;
}
It is just a small header file and does most of the simple stuff you need without using a big template-based approach like boost (no offence, I like boost!).
How to get file names in a directory one-by-one?
Pathlib.iterdir() offers a generator to iterate through directories, which reduces memory consumption:
import sys
import pathlib
import os
path = '/cache/srtm'
pl = pathlib.Path(path).iterdir()
oslb = os.listdir(path)
print(type(pl))
print (type(oslb))
print ('pathlib.iter: %s' % sys.getsizeof(pl))
print ('os.listdir: %s' % sys.getsizeof(oslb))
Prints:
<class 'generator'>
<class 'list'>
pathlib.iter: 88
os.listdir: 124920
Read file names from directory in Bash
To make the smallest change that fixes the problem:
dir="path to the files"
for f in "$dir"/*; do
cat "$f"
done
To accomplish what you describe as your desired end goal:
shopt -s nullglob
dir="path to the files"
substrings=( R1 R2 )
for substring in "${substrings[@]}"; do
cat /dev/null "$dir"/*"$substring"* >"${substring}.out"
done
Note that cat
can take multiple files in one invocation -- in fact, if you aren't doing that, you usually don't need to use cat at all.
Batch File : Read File Names from a Directory and Store in Array
Simulating Array
String is the only variable type in batch file. However, arrays can be simulated with several variables of identical name except a trailing numerical ID such as:
Array[1] Array[2] Array[3] Array[4] etc...
We can store each file name into these variables.
Retrieving command output
The first step is to put the command output into a variable. We may use the for /f
loop.
for /f %%G in ('dir *.txt /b') do set filename=%%~G
The ('')
clause and /f
option specifies to collect the command output. Note that the filename you get is always the last one displayed because of variable-overwriting. This can be resolved by appending instead, but is beyond the scope of this answer.
Giving ID to files
In this case, I will name the array filename
with a trailing ID [n]
, where n
is a numerical ID.
setlocal enableDelayedExpansion
set /a ID=1
for /f "delims=" %%G in ('dir *.txt /b') do (
set filename[!ID!]=%%~G
set /a ID+=1
)
set filename
endlocal
Two things to note:
I have added
"delims="
into the loop to ensure it works properly with default delimiters.I replaced
%ID%
with!ID!
because of delayed expansion. In short, when delayed expansion is disabled, the entire for loop is phrased before runtime, variables with new values are not updated block(()
) structures; if enabled, the said variables are updated.!ID!
indicates the need for update in each loop.
Batch File; List files in directory, only filenames?
The full command is:
dir /b /a-d
Let me break it up;
Basically the /b
is what you look for.
/a-d
will exclude the directory names.
For more information see dir /?
for other arguments that you can use with the dir
command.
read file name from directory
. is for current dir
.. is for one directory up
When using readdir you will get those 2 extra.
I prefer using glob(). That function lets you filter for html files only too
<?php
$files = glob('dir/*html');
foreach($files as $file) {
echo "filename:".$file."<br />";
}
?>
Related Topics
Why Is Std::Iterator Deprecated
Waiting Thread Until a Condition Has Been Occurred
Is It Bad Practice to Allocate Memory in a Dll and Give a Pointer to It to a Client App
Does "Undefined Behaviour" Extend to Compile-Time
How to Use C++ Preprocessor Stringification on Variadic MACro Arguments
Getting Big Random Numbers in C/C++
Comparing Character Arrays and String Literals in C++
How to Install Feature Based on the Property Set in Custom Action
Differencebetween Cout, Cerr, Clog of iOStream Header in C++? When to Use Which One
Why Does This Call the Default Constructor
Initializing Std::String from Char* Without Copy
Is There C/C++ Equivalent of Eval("Function(Arg1, Arg2)")
Gcc - How to Create a Mapfile of the Object File
How to Check If Window Is "Always on Top"
Ostream Chaining, Output Order
How to Use a Timer in C++ to Force Input Within a Given Time