How to use strcpy and strcat in C ++?

-2

How to use strcpy and strcat to get the names of the txt files in a directory within the application in a folder called value.

    
asked by anonymous 26.05.2015 / 15:38

1 answer

2

The functions (strcpy and strcat) and the listing of the files of a directory are very different subjects, strcpy and strcat are only functions to copy and to contact strings and are used in this case only to generate the directory where the files will be listed and not to list the files in a directory.

Both directory management and directory listing can be done in a variety of ways, in most cases "dirent.h" is used to list a directory, but I use the win32 API itself to perform this task.

This is the way I find it easier to use the Win32 API:

#include <windows.h>
#include <tchar.h> 
#include <stdio.h>
#include <vector>

using namespace std;

vector<wstring> GetFilesFromDirectory(wstring strDir)
{
   vector<wstring> AllFiles;
   WIN32_FIND_DATA ffd;
   HANDLE hFind = INVALID_HANDLE_VALUE;
   //
   strDir += L"\*";
   //
   hFind = FindFirstFile(strDir.c_str(), &ffd);
   //
   do
   {
      if (!(ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY))
      {
         AllFiles.push_back(wstring(ffd.cFileName));
      }
   }
   while (FindNextFile(hFind, &ffd) != 0);
   //
   FindClose(hFind);
   return AllFiles;
}

int main()
{
    // Lista os arquivos da pasta "C:\A"
    vector<wstring> files = GetFilesFromDirectory(L"C:\A");

    for (int C = 0; C < files.size(); C++)
    {
        // Mostra na tela
        _tprintf(L" %s\n", files[C].c_str());
    }

    system("PAUSE");

}

As shown in the example above, strcpy or strcat was not used at any time since the wstring iterator was used, which made it easier to concatenate the string.

To use char instead of wstring, just do it as follows:

#include <windows.h>
#include <tchar.h> 
#include <stdio.h>
#include <vector>

using namespace std;

vector<string> GetFilesFromDirectory(wstring strDir)
{
   vector<string> AllFiles;
   WIN32_FIND_DATA ffd;
   HANDLE hFind = INVALID_HANDLE_VALUE;
   //
   strDir += L"\*";
   //
   hFind = FindFirstFile(strDir.c_str(), &ffd);
   //
   do
   {
      if (!(ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY))
      {
         wstring wideStr(ffd.cFileName);
         AllFiles.push_back(string(wideStr.begin(), wideStr.end()));
      }
   }
   while (FindNextFile(hFind, &ffd) != 0);
   //
   FindClose(hFind);
   return AllFiles;
}

int main()
{
    // Lista os arquivos da pasta "C:\A"
    vector<string> files = GetFilesFromDirectory(L"C:\A");

    for (int C = 0; C < files.size(); C++)
    {
        // Mostra na tela
        printf(" %s\n", files[C].c_str());
    }

    system("PAUSE");

}

This is the result of the execution and the folder listed:

I hope I have helped

    
26.05.2015 / 19:16