diff --git a/Rdutil.cc b/Rdutil.cc index 4142ffe..bc2d181 100644 --- a/Rdutil.cc +++ b/Rdutil.cc @@ -27,12 +27,17 @@ // class declaration #include "Rdutil.hh" +bool +Rdutil::trywritetofile(const std::string& filename) +{ + return !!std::ofstream(filename); +} + int Rdutil::printtofile(const std::string& filename) const { // open a file to print to - std::ofstream f1; - f1.open(filename.c_str(), std::ios_base::out); + std::ofstream f1(filename); if (!f1.is_open()) { std::cerr << "could not open file \"" << filename << "\"\n"; return -1; diff --git a/Rdutil.hh b/Rdutil.hh index 2bd629f..11e73c3 100644 --- a/Rdutil.hh +++ b/Rdutil.hh @@ -24,6 +24,13 @@ public: { } + /** + * opens the given file for writing and closes it again. + * @param filename + * @return true if it went ok + */ + static bool trywritetofile(const std::string& filename); + /** * print file names to a file, with extra information. * @param filename diff --git a/rdfind.cc b/rdfind.cc index c64ad42..d37fae6 100644 --- a/rdfind.cc +++ b/rdfind.cc @@ -91,6 +91,17 @@ main(int narg, const char* argv[]) global_options = &o; dirlist.setcallbackfcn(&report); + if (o.makeresultsfile) { + // make sure the results file can be opened, before doing all potentially + // lengthy work. in case of permission problems, it is not fun to find out + // only after the fact. see https://github.com/pauldreik/rdfind/issues/128 + if (!Rdutil::trywritetofile(o.resultsfile)) { + std::cerr << "could not write to results file \"" << o.resultsfile + << "\"\n"; + std::exit(EXIT_FAILURE); + } + } + // now loop over path list and add the files // done with arguments. start parsing files and directories!