2

Hey so this is probably a dumb beginner question.

I want to write the filename of all .txt files from a folder inside a const char* array[].

So I tried to do it like this:

const char* locations[] = {"1"};
bool x = true;
int i = 0;    

LPCSTR file = "C:/Folder/*.txt";
WIN32_FIND_DATA FindFileData;

HANDLE hFind;
hFind = FindFirstFile(file, &FindFileData);
if (hFind != INVALID_HANDLE_VALUE)
{
    do 
    {
        locations.append(FindFileData.cFileName); //Gives an error
        i++;
    }
    while (FindNextFile(hFind, &FindFileData));
    FindClose(hFind);
}
cout << "number of files " << i << endl;

Basically the code should add the Filename of the .txt file to the const char* locations array but it doesn't work using append as it gives me the error: "C++ expression must have class type but it has type ''const char *''"

So how do I do it right?

  • Short answer: use `std::vector`. – Brian61354270 Dec 04 '21 at 21:19
  • hey @Brian you want me to use std::vector instead? I ll need the const char* locations[] format for an array listbox. how would I convert that? tried it with std::vectorlocations; and locations.push_back(FindFileData.cFileName); now. How can i make that to an array? – Discord Programs Dec 04 '21 at 21:29
  • Use a vector. Then `locations[ i ].data()` will return the `char*` pointer to the underlying buffer of `std::string`. – digito_evo Dec 04 '21 at 21:31

1 Answers1

3

Problem:

  1. You can't append items to a C array -T n[]- because the length of the array is determined at compile time.
  2. An array is a pointer(which is a scalar type), which isn't an object and doesn't have methods.

Solution:

The easiest solution is to use an std::vector which is a dynamic array:

#include <vector>
// ...
std::vector<T> name;

// or if you have initial values...
std::vector<T> name = {
    // bla bla bla..
};

In your case an array called location of strings is std::vector<std::string> locations.
For some reason, C++ containers don't like the classical append(), and provide the following methods:

container.push_back();  // append.
container.push_front(); // prepend.
container.pop_back();   // remove last
container.pop_front();  // remove first

Note that std::vector only provides push_back and pop_back

See:

Ahmed Shaqanbi
  • 525
  • 5
  • 15
  • An array is not a pointer. – Peter Dec 05 '21 at 02:06
  • @Peter An array **is** a pointer to _elements × 1 element size_ length chunk of memory. Also `int a[5]; std::cout << a << std::endl;` prints an address. – Ahmed Shaqanbi Dec 05 '21 at 07:51
  • An array can be converted to a pointer (to its first element) but is something different. There are contexts when assuming an array is a pointer works, and others where it fails. If what you say is true, the discussion in this link would be moot. https://stackoverflow.com/questions/1461432/what-is-array-to-pointer-decay – Peter Dec 05 '21 at 17:59