Created
July 9, 2014 23:07
-
-
Save LilinYume/ae3f8b463436b45779b9 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 <iostream> | |
#include <fstream> | |
using namespace std; | |
//--------------------------------------------------- | |
// 空のファイルか判定 | |
//--------------------------------------------------- | |
bool empty_file( std::fstream& fs ); | |
//--------------------------------------------------- | |
//--------------------------------------------------- | |
// ファイル末尾の値を取得 | |
// 改行コードを付加 | |
//--------------------------------------------------- | |
enum newline{ cr, lf, crlf }; | |
char get_end( std::fstream& fs ); | |
void set_newline( std::fstream& fs ,newline code ); | |
//--------------------------------------------------- | |
int main() | |
{ | |
fstream f ( "tmp", ios::binary | ios::in | ios::out ); | |
f << "abc"; | |
return 0; | |
} | |
bool empty_file( std::fstream& fs ) | |
{ | |
// オープンされているかチェック | |
if ( !fs ) { | |
std::cerr << "something went wrong\n"; | |
exit( EXIT_FAILURE ); | |
} | |
// ファイルの現在位置を退避 | |
std::ios::pos_type cur_pos = fs.tellg(); | |
char check = -1; | |
std::ios::pos_type start = 0; | |
// ファイル先頭から開くことを保証 | |
fs.seekg( start ); | |
// 一文字取得 | |
fs.get( check ); | |
if ( !fs ) { /* fs.eof() */ | |
fs.clear(std::ios::goodbit); | |
return true; | |
} | |
// ストリームと現在位置をキレイにしてから返す | |
fs.putback( check ); | |
fs.seekg( cur_pos ); | |
return false; | |
} | |
char get_end( std::fstream& fs ) | |
{ | |
// オープンされているかチェック | |
if ( !fs ) { | |
std::cerr << "something went wrong\n"; | |
exit( EXIT_FAILURE ); | |
} | |
if ( empty_file( fs ) == true ) return -1; | |
// ファイルの現在位置を退避 | |
std::ios::pos_type cur_pos = fs.tellg(); | |
// ファイル末尾の1Byte手前から開く | |
std::ios::pos_type tail = -1; | |
fs.seekg( tail, std::ios::end ); | |
char last = -1; | |
fs.get( last ); | |
// ストリームと現在位置をキレイにしてから返す | |
fs.putback( last ); | |
fs.seekg( cur_pos ); | |
return last; | |
} | |
void set_newline( std::fstream& fs ,newline code ) | |
{ | |
char last = get_end(fs); | |
if ( last == 0x0d || last== 0x0a ) return; | |
// ファイルの現在位置を退避 | |
std::ios::pos_type cur_pos = fs.tellg(); | |
// ファイル末尾から開く | |
std::ios::pos_type tail = 0; | |
fs.seekg( tail, std::ios::end ); | |
switch ( code ) { | |
case cr: | |
fs.put( 0x0d ); | |
break; | |
case lf: | |
fs.put( 0x0a ); | |
break; | |
case crlf: | |
fs.put( 0x0d ).put( 0x0a ); | |
break; | |
default: | |
std::cout << "not listed" << std::endl; | |
break; | |
} | |
// ストリームと現在位置をキレイにする | |
fs.putback( last ); | |
fs.seekg( cur_pos ); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment