Storing list of file names as a string array?

Pages: 12
closed account (Dy7SLyTq)
sigh... that is to be a programmer
https://www.facebook.com/photo.php?fbid=532350683480481&set=pb.241806149201604.-2207520000.1375471668.&type=3&theater

except me: i have never written code with a bug... the compiler just optimized it wrong ;)
Last edited on
A better design:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#include <iostream>
#include <string>
#include <vector>
#include <Windows.h>

std::vector<std::string> getFileNames(const std::string&);

template <typename iter_type>
void printSequence(iter_type beg, iter_type end, std::ostream& os = std::cout, char sep = '\n')
{
    while (beg != end)
        os << *beg++ << sep;
}

int main()
{
    // const std::string spec("C:/textfiles/*.txt");
    const std::string spec("/projects/testdir/*.txt");

    std::vector<std::string> list = getFileNames(spec);

    if (list.size())
        printSequence(list.begin(), list.end());
    else
        std::cout << "No matching files.\n";
}

std::vector<std::string> getFileNames(const std::string& spec)
{
    std::vector<std::string> filenames;

    WIN32_FIND_DATA search_data = {};

    HANDLE handle = FindFirstFileA(spec.c_str(), &search_data);

    if (handle != INVALID_HANDLE_VALUE)
    {
        do
        {
            filenames.push_back(search_data.cFileName);
        } while (FindNextFileA(handle, &search_data));
    }

    return filenames;
}
Last edited on
Nice. I really like the printSequence function!
Whats the difference in functionality from cire's to the code im using? or is it just more effecient?
The main difference is that the specification for the files you're looking for are not hard coded into the function (which is the design alluded to.) It is good to have flexible code.

[Edit: One other notable difference is that I used the xxxA version of the find functions which means the code won't break if compiler settings are changed and unicode is enabled.]
Last edited on
Topic archived. No new replies allowed.
Pages: 12