Last active
August 29, 2015 14:02
-
-
Save nekko1119/940b5a739914f60ea346 to your computer and use it in GitHub Desktop.
ファイルの空行を消して上書きするプログラム
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <algorithm> | |
#include <iostream> | |
#include <iterator> | |
#include <fstream> | |
#include <regex> | |
#include <string> | |
#include <vector> | |
#include <boost/optional.hpp> | |
using namespace std; | |
string const help_message = | |
R"( | |
書式: | |
delln <テキストファイル名> | |
テキストファイルを必ず1つ渡して下さい。 | |
0または2以上は不正です。 | |
)"; | |
// コマンドライン引数が妥当か判断する | |
bool validates(int arg, char const* const* argv) { | |
if (arg != 2) { | |
cout << "引数の数が正しくありません。" << help_message << endl; | |
return false; | |
} | |
return true; | |
} | |
// ファイルの空行を削除する | |
auto remove_empty_line(ifstream& ifs) -> vector<string> { | |
regex const pattern{"^\n", regex_constants::grep}; | |
vector<std::string> formatted; | |
string buffer; | |
while (getline(ifs, buffer)) { | |
if (!regex_match(buffer, pattern)) { | |
formatted.emplace_back(buffer); | |
} | |
} | |
return formatted; | |
} | |
// ファイルを開き、ファイルの中身を整形した文字列を返す | |
auto format_content(std::string const& filename) -> boost::optional<vector<string>> { | |
ifstream ifs{filename}; | |
if (!(ifs) || !ifs.is_open()) { | |
return boost::none; | |
} | |
return remove_empty_line(ifs); | |
} | |
int main(int argc, char** argv) { | |
// 引数チェック | |
if (!validates(argc, argv)){ | |
return 1; | |
} | |
if (auto const result = format_content(argv[1])) { | |
ofstream ofs(argv[1], ios_base::out | ios_base::trunc); | |
copy(cbegin(*result), cend(*result), ostream_iterator<string>(ofs, "\n")); | |
cout << "完了しました。" << endl; | |
return 0; | |
} | |
cout << "ファイルを開けませんでした。終了します。" << endl; | |
return 1; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment