std::ios::in
std::ios::out
std::ios::binary
std::ios::ate
std::ios::in
或 std::ios::out
组合使用。std::ios::app
std::ios::trunc
std::ios::out
组合使用。这些标志可以通过按位或操作符 (|
) 组合使用。例如:
std::ios::in | std::ios::out
:以读写模式打开文件。std::ios::out | std::ios::app
:以写和追加模式打开文件。以下是一些使用不同文件模式标志的示例代码:
std::ios::in
)#include #include int main() { std::ifstream file("example.txt", std::ios::in); if (!file) { std::cerr << "File could not be opened for reading" << std::endl; return 1; } std::string line; while (std::getline(file, line)) { std::cout << line << std::endl; } file.close(); return 0; }
std::ios::out
)#include #include int main() { std::ofstream file("example.txt", std::ios::out); if (!file) { std::cerr << "File could not be opened for writing" << std::endl; return 1; } file << "Writing this text to the file." << std::endl; file.close(); return 0; }
std::ios::app
)#include #include int main() { std::ofstream file("example.txt", std::ios::app); if (!file) { std::cerr << "File could not be opened for appending" << std::endl; return 1; } file << "Appending this text to the file." << std::endl; file.close(); return 0; }
std::ios::binary
)#include #include int main() { std::fstream file("example.bin", std::ios::in | std::ios::out | std::ios::binary);