Skip to content

Instantly share code, notes, and snippets.

@nekko1119
Last active August 29, 2015 14:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nekko1119/940b5a739914f60ea346 to your computer and use it in GitHub Desktop.
Save nekko1119/940b5a739914f60ea346 to your computer and use it in GitHub Desktop.
ファイルの空行を消して上書きするプログラム
#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