There are several files in the folder. It is required to determine the type of each file and, depending on this, transfer it to one of the folders:

  • Exe.
  • CPP.
  • H.
  • Txt

It seems to be a simple formulation, but I can’t do it at all, no thoughts, help, if not difficult. Thank you in advance.

    4 answers 4

    As it seems to me, you need to dig in the direction of the function findfirst () and checking the string from the name by pattern . followed by sorting and rewriting to another directory.


    Well, as an option, write a shell script and run it from the application.


    UPD: here is a bit of code in which the search takes place; you only need to change a little (make a copy)

    #include <iostream> #include <Windows.h> using namespace std; int main(){ WIN32_FIND_DATA FindFileData; HANDLE hFind = INVALID_HANDLE_VALUE; // Find the first file in the directory. hFind = FindFirstFile("C:\\*.bin", &FindFileData); if (hFind == INVALID_HANDLE_VALUE) { printf ("Invalid file handle. Error is %u.\n", GetLastError()); } else { printf ("First file name is %s.\n", FindFileData.cFileName); // List all the other files in the directory. while (FindNextFile(hFind, &FindFileData) != 0){ printf ("Next file name is %s.\n", FindFileData.cFileName); } FindClose(hFind); } return 0; } 

      Enumerate the names of the files in the folder. Look for a period in the file name. Check the text after it, and if it fits into one of the specified, then rename the file, send it to the desired folder.

      In * nix, see manes for opendir, readdir, rename (for Windows, see their analogs in Google), as well as strchr, strcmp, strcpy (or snprintf) ...

        Then here’s one line on PowerShell:

         Get-ChildItem -Path *.cpp, *.h, *.exe, *.txt | ForEach-Object { Move-Item $_ -Destination $(Join-Path $_.Extension.Substring(1) $_.Name) } 

        Or a little longer in C #:

         var exts = new HashSet<string> { ".exe", ".cpp", ".h", ".txt" }; foreach (var fi in new DirectoryInfo(path).EnumerateFiles("*.cpp") .Where(fi => exts.Contains(fi.Extension))) fi.MoveTo(Path.Combine(path, fi.Extension.Substring(1), fi.Name)); 

          On Python:

           import os extensions = '.EXE', '.CPP', '.H', '.TXT' for name in os.listdir(): # всС ΠΈΠΌΠ΅Π½Π° Π² Ρ‚Π΅ΠΊΡƒΡ‰Π΅ΠΉ Π΄ΠΈΡ€Π΅ΠΊΡ‚ΠΎΡ€ΠΈΠΈ if name.upper().endswith(extensions): # имя ΠΈΠΌΠ΅Π΅Ρ‚ Π½ΡƒΠΆΠ½ΠΎΠ΅ Ρ€Π°ΡΡˆΠΈΡ€Π΅Π½ΠΈΠ΅ ext = os.path.splitext(name)[1] # ΠΈΠ·Ρ‹ΠΌΠ°Π΅ΠΌ Ρ€Π°ΡΡˆΠΈΡ€Π΅Π½ΠΈΠ΅ ΠΈΠ· ΠΈΠΌΠ΅Π½ΠΈ new_name = os.path.join(ext[1:].upper(), name) # Π½ΠΎΠ²ΠΎΠ΅ имя Π² ΡΠΎΠΎΡ‚Π²Π΅Ρ‚ΡΡ‚Π²ΡƒΡŽΡ‰Π΅ΠΉ Π΄ΠΈΡ€Π΅ΠΊΡ‚ΠΎΡ€ΠΈΠΈ os.replace(name, new_name) # пСрСносим