I'm trying to learn C++ having come from a C/Assembly background. I thought one of the first tools I'd make as a project is a "directory tally" program:
- It will count all the files in the current directory
- If the user specifies, it will count all the folders in the current directory too
- If the user specifies, it will count all the files in subdirectories as well (and folders if the user specifies)
Given that most of my academic, professional, and personal programming projects have involved C instead of C++ I'm pretty sure that my code is not idiomatic C++ (yet), but I have used guidelines like use std::(w)string
over (w)char(_t) *
strings, use the STL as much as possible, etc.
I'm wondering if I can get feedback on:
- Is it obvious from looking at my code that I come from a C background?
- What can I do to make this program look more like idiomatic C++?
- The usual code review stuff, things I could write more clearly or bad things I'm doing that I should avoid.
#include <iostream>
#include <filesystem>
namespace fs = std::experimental::filesystem;
bool __cdecl recur_flag(std::wstring arg)
{
if (arg.length() < 2) return false;
return ((arg.at(0) == L'-' || arg.at(0) == L'/') && (arg.at(1) == L'r' || arg.at(1) == L'R'));
}
bool __cdecl dir_flag(std::wstring arg)
{
if (arg.length() < 2) return false;
return ((arg.at(0) == L'-' || arg.at(0) == L'/') && (arg.at(1) == L'd' || arg.at(1) == L'D'));
}
bool __cdecl help_flag(std::wstring arg)
{
if (arg.length() < 2) return false;
return ((arg.at(0) == L'-' || arg.at(0) == L'/') && (arg.at(1) == L'?'));
}
int __cdecl wmain(int argc, wchar_t *argv[])
{
bool recur = false, dircount = false;
unsigned long long count = 0;
recur = ((argc >= 2) && (recur_flag(std::wstring(argv[1])))) || ((argc >= 3) && (recur_flag(std::wstring(argv[2]))));
dircount = ((argc >= 2) && (dir_flag(std::wstring(argv[1])))) || ((argc >= 3) && (dir_flag(std::wstring(argv[2]))));
if ((argc >= 2) && (help_flag(std::wstring(argv[1]))) || (argc >= 3) && (help_flag(std::wstring(argv[2]))))
{
std::wcout << L"Usage: dircount /R /D /?" << std::endl << L"\t/R Recursive - count files in current directory and subdirectories" << std::endl <<
L"\t/D Include directories when counting files" << std::endl << L"\t/? Display this help message" << std::endl << std::endl;
return 0;
}
if (recur)
{
for (auto &p : fs::recursive_directory_iterator(fs::current_path()))
{
if (fs::is_directory(p))
{
if (dircount) count++;
}
else count++;
}
}
else
{
for (auto &p : fs::directory_iterator(fs::current_path()))
{
if (fs::is_directory(p))
{
if (dircount) count++;
}
else count++;
}
}
std::wcout << L"There are " << count << L" items in the current directory"; if (recur) std::wcout << L" tree"; std::wcout << std::endl;
return 0;
}