C++ File list with all file informations - c++

I'm planning to make a program that would work between a folder on my computer and my NAS.
It would list all the files in both folders, then determine which file is newer, and then upload it to the other device.
I know how to upload files via FTP, but I'm stuck at the start, because I don't know how to list my files. I have looked a little at using FindFirstFile() and FindNextFile() with WIN32_FIND_DATA. This way, I can get the last write data, but this doesn't let me list subdirectories.
Do you know any easy way listing all files in a folder and its subdirectory and saving the information of every file in a list?

The easy way is to use boost::recursive_directory_iterator.
#include <boost/foreach.hpp>
#include <iostream>
#include <vector>
#include <boost/filesystem.hpp>
#include <boost/date_time.hpp>
#include <algorithm>
#include <iterator>
#include <ctime>
using boost::filesystem::path;
using boost::filesystem::recursive_directory_iterator;
using boost::filesystem::directory_entry;
using boost::filesystem::filesystem_error;
using boost::filesystem::last_write_time;
using std::vector;
using std::cout;
using std::copy;
using std::ostream_iterator;
using std::time_t;
using boost::posix_time::from_time_t;
int main(int ac, const char **av)
{
vector<const char*> args(av+1, av+ac);
if(args.empty())
args.push_back(".");
vector<directory_entry> files;
BOOST_FOREACH(path p, args)
{
boost::system::error_code ec;
copy(recursive_directory_iterator(p, ec),
recursive_directory_iterator(),
back_inserter(files));
}
BOOST_FOREACH(const directory_entry& d, files)
{
if(exists(d.path()))
{
cout << from_time_t(last_write_time(d.path())) << " " << d.path() << "\n";
}
}
}

FindFirstFile() and FindNextFile() does let you list subdirectories. One of the members of WIN32_FIND_DATA is dwFileAttributes which will include FILE_ATTRIBUTE_DIRECTORY for a directory entry. Simply start another FindFirstFile() in that subdirector, rinse, repeat.
There is a sample on MSDN that shows how to use the FindFirstFile API, here.

Related

JsonCpp can't find file when I use get_current_dir_name()

I am trying to parse a json file within my program:
#include <jsoncpp/json/value.h>
#include <jsoncpp/json/json.h>
#include <unistd.h>
#include <stdio.h>
int main(){
std::string plan { get_current_dir_name() };
plan += "directory/file.json";
read_json(plan); // A function that reads a json file using jsoncpp
}
Output:
Error: Json File not found!
However when I manually write the entire path:
#include <jsoncpp/json/value.h>
#include <jsoncpp/json/json.h>
#include <unistd.h>
#include <stdio.h>
int main(){
std::string plan { entire_file_path };
read_json(plan); // A function that reads a json file using jsoncpp
}
Output:
File found and read!
I thought maybe there is a spelling mistake but when I use std::cout on both of the paths, there is not a single difference. I'm not sure what is causing this issue.
Using std::filesystem built-in to C++17:
namespace fs = std::filesystem;
fs::path path = fs::current_path() / "directory" / "file.json";
read_json(path.string());

How to use a buffer while writing to a file with c++ boost streams?

I'm trying to write some strings on a txt file using "Boost C++" libraries but i cannot find online a complete guide about how to do that.
The only thing i have been able to do is this:
#include <ostream>
#include <boost/iostreams/device/file.hpp>
#include <boost/iostreams/stream.hpp>
namespace io = boost::iostreams;
using namespace std;
io::stream_buffer<io::file_sink> buf("test.txt");
ostream out(&buf);
out<<"Hello world!"<<flush;
that simply writes a simple string on the file.
How can i set the buffer size? Is there a way to implement an auto flushing cycle?

Loading output of System (char* command) to variable, c++

...Am trying to load/capture the output of system(char* command) function to a variable, a vector. can i have any possible way to push the output to my vector? I don*t want to write the output to file and read it again.
Sample code:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fstream>
#include <iostream>
#include <string>
#include <cstring>
#include <sstream>
#include <vector>
using namespace std;
int main()
{
vector <string> dir;
system("pwd");//here i used this to print the current directory, and i want to store this out put to my vector. something like...(below )
output=output of system("pwd");//this is not a real code,just to notice i want to put the out put to other var and push.
dir.push_back(output);
return 0;
}
Can i have any scenario to do this task, thanks.
I'd recommend doing it like this:
FILE *fp = popen("fortune","r");
char line[200];
while(!feof(fp)) {
fgets(line,200,fp);
// process here
}
pclose(fp);
If it's really performance critical it's probably better to
create a child process using fork() and pipes for stdin/stdout of that child
process to write or read from.
An example of this could be found here (http://www.microhowto.info/howto/capture_the_output_of_a_child_process_in_c.html#idp21888) if you're intested. But the popen method is probably the most simple and straightforward one in your case.

find and move files in C++

I'm new to C++ and I've just read <C++ Primer> 4ed. Now I want to implement a little program to help me manage some mp3 files in my computer.
I have a .txt file which includes all the names(part of the names actually) of the files which I want to move(not copy) to a new folder(in the same column). For example, "word" and "file" in the .txt and I want to move all the .mp3 files whose filename contain "word" or "file" to a new folder. Hope my discription is clear, Opps..
I know how to read the strings in .txt into a set<string> and traverse it, but I have no idea how to search and move a file in a folder. I just want to know what else should I learn so that I can implement this function. I read C++ Primer and still I can't do much thing, that's really sad...
To move a file in C++, you do not have to use external libraries like Boost.Filesystem, but you can use standard functionality.
There is the new filesystem API, which has a rename function:
#include <iostream>
#include <filesystem>
int main() {
try {
std::filesystem::rename("from.txt", "to.txt");
} catch (std::filesystem::filesystem_error& e) {
std::cout << e.what() << '\n';
}
return 0;
}
The drawback is to compile it, you need a recent C++17 compiler. (I tested it on gcc 8.0.1, and I also needed to link against -lstdc++fs).
But what should work on any C++ compiler today, is the old C API, which also provides rename (cstdio):
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cerrno>
int main() {
if(std::rename("from.txt", "to.txt") < 0) {
std::cout << strerror(errno) << '\n';
}
return 0;
}
But note that in both cases, the rename will fail if the source and destination files are not on the same filesystem. Then you will see an error like this:
filesystem error: cannot rename: Invalid cross-device link [from.txt] [/tmp/to.txt]
In that case, you can only make a copy and then remove the original file:
#include <fstream>
#include <iostream>
#include <ios>
#include <cstdio>
int main() {
std::ifstream in("from.txt", std::ios::in | std::ios::binary);
std::ofstream out("to.txt", std::ios::out | std::ios::binary);
out << in.rdbuf();
std::remove("from.txt");
}
Or with the new API:
#include <iostream>
#include <filesystem>
int main()
{
try {
std::filesystem::copy("from.txt", "to.txt");
std::filesystem::remove("from.txt");
} catch (std::filesystem::filesystem_error& e) {
std::cout << e.what() << '\n';
}
return 0;
}
Use rename() function to move a file
#include <iostream>
#include <cstdio>
using namespace std;
int main()
{
char oldname[] = "C:\\Users\\file_old.txt";
char newname[] = "C:\\Users\\New Folder\\file_new.txt";
/* Deletes the file if exists */
if (rename(oldname, newname) != 0)
perror("Error moving file");
else
cout << "File moved successfully";
return 0;
}
The only way for this to work only using std would be to read the file completely using a std::ifstream and then write it to the new location with a std::ofstream. This will however not remove the old file from disk. So basically you create a copy of the file. Its also much slower than a real move.
The optimal solution is to use OS specific APIs like win32 which e.g provide a MoveFile() function. Poco provides an platform independent abstraction of such APIs. See: http://www.appinf.com/docs/poco/Poco.File.html
Another way to move a file in Windows is using the MoveFile function as it is shown in the following code.
std::wstring oldPath = L"C:\\Users\\user1\\Desktop\\example\\text.txt";
std::wstring newPath = L"C:\\Users\\user1\\Desktop\\example1\\text.txt";
bool result = MoveFile(newPath.c_str(), oldPath.c_str());
if (result)
printf("File was moved!");
else
printf("File wasn't moved!");
under Windows run system call with batch commands:
system("move *text*.mp3 new_folder/");
system("move *word*.mp3 new_folder/");
Under Unix same with shell syntax.

Check if file exists in C++

I'm very very new to C++.
In my current project I already included
#include <iostream>
#include <Windows.h>
#include <TlHelp32.h>
and I just need to do a quick check in the very beginning of my main() to see if a required dll exists in the directory of my program.
So what would be the best way for me to do that?
So, assuming it's OK to simply check that the file with the right name EXISTS in the same directory:
#include <fstream>
...
void check_if_dll_exists()
{
std::ifstream dllfile(".\\myname.dll", std::ios::binary);
if (!dllfile)
{
... DLL doesn't exist...
}
}
If you want to know that it's ACTUALLY a real DLL (rather than someone opening a command prompt and doing type NUL: > myname.dll to create an empty file), you can use:
HMODULE dll = LoadLibrary(".\\myname.dll");
if (!dll)
{
... dll doesn't exist or isn't a real dll....
}
else
{
FreeLibrary(dll);
}
There are plenty ways you can achieve that, but using boost library is always a good way.
#include <boost/filesystem.hpp>
using boost::filesystem;
if (!exists("lib.dll")) {
std::cout << "dll does not exists." << std::endl;
}