c++のファイル読み書き関数
4046 ワード
ヘッダファイル、ネーミングスペース
リファレンスマニュアル
CPP参考マニュアル中国語https://zh.cppreference.com/w/%E9%A6%96%E9%A1%B5
CPP参考マニュアルhttps://en.cppreference.com/w/
#include
using name space std;
//
// , 。
explicit basic_ifstream( const char* filename,
std::ios_base::openmode mode = ios_base::in ); (2)
explicit basic_ifstream( const std::string& filename,
std::ios_base::openmode mode = ios_base::in ); (4) (since C++11)
explicit basic_ifstream( const std::filesystem::path& filename,
std::ios_base::openmode mode = ios_base::in ); (5) (since C++17)
basic_ifstream( basic_ifstream&& other ); (6) (since C++11)
/*
explicit https://baike.baidu.com/item/explicit/4941869?fr=aladdin
filename: char* string& , , "\\"
mode: ios_base::openmode,
ios::in (ifstream )
ios::out (ofstream )
ios::app
ios::ate
ios::trunc
ios::nocreate( ) , open()
ios::noreplace ( ) , open() 。
ios::binary ,
,
: 。 int. 0x40, 。
#define _SH_DENYRW 0x10 /* deny read/write mode */
#define _SH_DENYWR 0x20 /* deny write mode */
#define _SH_DENYRD 0x30 /* deny read mode */
#define _SH_DENYNO 0x40 /* deny none mode */
#define _SH_SECURE 0x80 /* secure mode */ ,
*/
/* */
bool is_open(); (until C++11)
bool is_open() const; (since C++11)
//
#include
#include
#include
//this file is called main.cpp
bool file_exists(const std::string& str)
{
std::ifstream fs(str);
return fs.is_open();
}
int main()
{
std::boolalpha(std::cout);
std::cout << file_exists("main.cpp") << '
'
<< file_exists("strange_file") << '
';
}
/*
basic_istream& getline( char_type* s, std::streamsize count );
(1)
basic_istream& getline( char_type* s, std::streamsize count, char_type delim );
(2)
*/
//
#include
#include
#include
#include
int main()
{
std::istringstream input("abc|def|gh");
std::vector<:array>> v;
// note: the following loop terminates when std::ios_base::operator bool()
// on the stream returned from getline() returns false
for (std::array a; input.getline(&a[0], 4, '|'); ) {
v.push_back(a);
}
for (auto& a : v) {
std::cout << &a[0] << '
';
}
}
/*
basic_istream& read( char_type* s, std::streamsize count );
*/
//
#include
#include
#include
#include
#include
int main()
{
// read() is often used for binary I/O
std::string bin = {'\x12', '\x12', '\x12', '\x12'};
std::istringstream raw(bin);
std::uint32_t n;
if(raw.read(reinterpret_cast(&n), sizeof n))
std::cout << std::hex << std::showbase << n << '
';
// prepare file for next snippet
std::ofstream("test.txt", std::ios::binary) << "abcd1
abcd2
abcd3";
// read entire file into string
if(std::ifstream is{"test.txt", std::ios::binary | std::ios::ate}) {
auto size = is.tellg();
std::string str(size, '\0'); // construct string to stream size
is.seekg(0);
if(is.read(&str[0], size))
std::cout << str << '
';
}
}
リファレンスマニュアル
CPP参考マニュアル中国語https://zh.cppreference.com/w/%E9%A6%96%E9%A1%B5
CPP参考マニュアルhttps://en.cppreference.com/w/