Getting Names of files in C++

Posted on 2011-10-19
Last Modified: 2012-05-12

I require a code in C++ that will retrieve all the names of the files in the current directory from which it is executed.
         D:\My docs\file 1.txt
         D:\My docs\file 2.txt

  It should return "file 1.txt" and "file 2.txt"

thank you
Question by:devguru001
    LVL 32

    Accepted Solution

    at windows you would use FindFirstFile and FindNextFile.

    WIN32_FIND_DATA FindFileData;
    HANDLE hFind = FindFirstFile("D:\\My Docs\\*.txt", &FindFileData);
    if (hFind != INVALID_HANDLE_VALUE) 
         std::cout << "The first file found is " << FindFileData.cFileName << std::endl;

    Open in new window

    you would call FindNextFile in a loop to get more files and finally a FindClose to release the handle.

    LVL 53

    Expert Comment


    Author Closing Comment

    Thanks alot Sara.... I was running the code under MS VS 2010 and got tons of errors.  Decided to instal Dev C++ and it works.... thanks again....
    LVL 32

    Expert Comment

    you should get solved the tons of errors by using project type 'win32 console application', switch-off precompiled header in the project settings and include <windows.h>. i assume you used 'managed c++' project which has some restrictions for using (unmanaged) c++ code.

    but Dev C++ is a good choice either.


    Featured Post

    Why You Should Analyze Threat Actor TTPs

    After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

    Join & Write a Comment

    In days of old, returning something by value from a function in C++ was necessarily avoided because it would, invariably, involve one or even two copies of the object being created and potentially costly calls to a copy-constructor and destructor. A…
    This article shows you how to optimize memory allocations in C++ using placement new. Applicable especially to usecases dealing with creation of large number of objects. A brief on problem: Lets take example problem for simplicity: - I have a G…
    The viewer will learn how to use the return statement in functions in C++. The video will also teach the user how to pass data to a function and have the function return data back for further processing.
    The viewer will be introduced to the technique of using vectors in C++. The video will cover how to define a vector, store values in the vector and retrieve data from the values stored in the vector.

    732 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    18 Experts available now in Live!

    Get 1:1 Help Now