Skip to content
Fix Code Error

How can I get the list of files in a directory using C or C++?

March 13, 2021 by Code Error
Posted By: samoz

How can I determine the list of files in a directory from inside my C or C++ code?

I’m not allowed to execute the ls command and parse the results from within my program.

Solution

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 which is also available for windows:

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 ("%sn", 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!).

The author of the windows compatibility layer is Toni Ronkko. In Unix, it is a standard header.

Answered By: Peter Parker

Related Articles

  • C++ template,typename and operator
  • What are the new features in C++17?
  • easiest way to extract Oracle form xml format data
  • Issue with iron-ajax request
  • How to generate JAXB classes from XSD?
  • Callback functions in C++
  • Copy a file in a sane, safe and efficient way
  • no match for ‘operator
  • Output not incrementing correctly - C++
  • Why does this core dumped error happen in my class?…
  • Head pointer not accessible when creating a method…
  • How do i arrange images inside a div?
  • C++ error: expected class member or base class name…
  • Is it possible to print a variable's type in standard C++?
  • OOP can't get value from a class
  • Trying to overload operator
  • I'm getting an error "invalid use of incomplete type…
  • How do i calculate total without manually inputting it?
  • unique_ptr is not deleted after calling reset
  • Gradle error: Execution failed for task…
  • What is the issue with this QOpenGLWidget?
  • Baffling variadic templates exercise
  • How to properly do JSON API GET requests and assign…
  • npm install error in vue
  • Getting weird compilation error in defining a…
  • is there a way to use the forwarding of std::less…
  • org.gradle.api.tasks.TaskExecutionException:…
  • How do I print out the contents of a vector?
  • Reading and writing to serial port in C on Linux
  • implementing merge sort in C++
  • Best substitute for goto in C++ as beginner for use…
  • "Undefined reference to" template class constructor
  • Make datetime derived from one column
  • Qt program with OpenGL + GLSL integration crashes…
  • What are the undocumented features and limitations…
  • Replacing a 32-bit loop counter with 64-bit…
  • I do not use TBB, but I get linker errors related to TBB
  • How to add Typescript to a Nativescript-Vue project?
  • Error: Expression must have integral or unscoped enum type
  • Dodged bar plot in R based on to columns with count…
  • C++ Need help sorting a 2D string array
  • Why are elementwise additions much faster in…
  • Pointer to incomplete class type is not allowed
  • How to write a large buffer into a binary file in C++, fast?
  • C++ "else" statement when the preceding line has…
  • how do I replace a static array with a dynamic one?
  • problem with client server unix domain stream…
  • c++ how to align output with for loop
  • Is it possible to declare two variables of different…
  • Overload resolution between va_list and ellipsis…
  • How to convert wstring into string?
  • Overloading operators in typedef structs (c++)
  • Jetpack Compose and Hilt Conflict
  • How to parse an RSS feed using JavaScript?
  • Base type is not converting to derived type yet can…
  • Iterating over llvm::Function to get pass result
  • Eigen 3x3 matrix inverse wrong result
  • The 'compilation' argument must be an instance of…
  • Error: Jump to case label
  • How can I create an executable to run a kernel in a…
  • Converting complex table with groupings in r to dataframe
  • How to filter a RecyclerView with a SearchView
  • Effectively getting items from map based on specific sort
  • Checking cin input stream produces an integer
  • Strange thing with linked list
  • Why is 2 * (i * i) faster than 2 * i * i in Java?
  • C++ OpenGL stb_image.h errors
  • How to generate 2,598,960 hands (efficient way) for…
  • C++ printing boolean, what is displayed?
  • Example of AES using Crypto++
  • What is the life time of a in "auto&& a=…
  • using reference pointer type as Paramter in c++
  • Execution failed for task…
  • C++: Print out enum value as text
  • I have tried to implement mergesort and am unable to…
  • What are access specifiers? Should I inherit with…
  • How do SO_REUSEADDR and SO_REUSEPORT differ?
  • How to format a phone number in a textfield
  • Adding gif image in an ImageView in android
  • long long int vs. long int vs. int64_t in C++
  • Fastest way to iterate over all the chars in a String
  • What's the difference between eval, exec, and compile?
  • Undefined Reference to
  • Why does C++ code for testing the Collatz conjecture…
  • C# parse FHIR bundle - read resources
  • Segmentation Core Dump Problem in Dijkstra Algorithm
  • How to generate a random number in C++?
  • error: strcpy was not declared in this scope
  • Docker compose fails to start a service with an…
  • fast c++ sign function
  • What does "#include " do?
  • How to use html template with vue.js
  • How can I find the product GUID of an installed MSI setup?
  • Error: the entity type requires a primary key
  • What is a NullReferenceException, and how do I fix it?
  • Getting the highest value of an JSON array and…
  • Fatal error: iostream: No such file or directory in…
  • Undefined reference to 'vtable for ✘✘✘'
  • How to parse JSON with XE2 dbxJSON
  • Why is my function continuing even after I give it…

Disclaimer: This content is shared under creative common license cc-by-sa 3.0. It is generated from StackExchange Website Network.

Post navigation

Previous Post:

How can I check if a single character appears in a string?

Next Post:

java.net.ConnectException: Connection refused

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

.net ajax android angular arrays aurelia backbone.js bash c++ css dataframe ember-data ember.js excel git html ios java javascript jquery json laravel linux list mysql next.js node.js pandas php polymer polymer-1.0 python python-3.x r reactjs regex sql sql-server string svelte typescript vue-component vue.js vuejs2 vuetify.js

  • you shouldn’t need to use z-index
  • No column in target database, but getting “The schema update is terminating because data loss might occur”
  • Angular – expected call-signature: ‘changePassword’ to have a typedeftslint(typedef)
  • trying to implement NativeAdFactory imports deprecated method by default in flutter java project
  • What should I use to get an attribute out of my foreign table in Laravel?
© 2022 Fix Code Error