Working With Files and Directories
Desliza para mostrar el menú
When building cross-platform console applications in C++, handling files and directories is a common requirement. The C++ Standard Library provides two key components for this purpose: std::filesystem and std::fstream. The std::filesystem library, introduced in C++17 and improved in later standards, gives you a portable way to work with paths, directories, and file operations. std::fstream allows you to read from and write to files in a straightforward, stream-oriented manner.
Using these standard libraries ensures that your code works reliably across different operating systems, such as Windows, macOS, and Linux, without needing to use platform-specific APIs. You can create, check for existence, read, write, and manipulate files and directories using familiar and consistent C++ syntax.
file_demo.cpp
12345678910111213141516171819202122232425262728293031323334353637383940414243444546#include <iostream> #include <fstream> #include <filesystem> int main() { namespace fs = std::filesystem; const fs::path dir = "example_dir"; const fs::path file = dir / "sample.txt"; // Create directory if it doesn't exist if (!fs::exists(dir)) { fs::create_directory(dir); std::cout << "Directory created: " << dir << '\n'; } else { std::cout << "Directory already exists: " << dir << '\n'; } // Write to file std::ofstream ofs(file); if (ofs) { ofs << "Hello from cross-platform C++!\n"; ofs << "This is a sample text file.\n"; ofs.close(); std::cout << "Data written to file: " << file << '\n'; } else { std::cerr << "Failed to open file for writing: " << file << '\n'; return 1; } // Read from file std::ifstream ifs(file); if (ifs) { std::cout << "Reading from file: " << file << '\n'; std::string line; while (std::getline(ifs, line)) { std::cout << line << '\n'; } ifs.close(); } else { std::cerr << "Failed to open file for reading: " << file << '\n'; return 1; } return 0; }
This program demonstrates how to create a directory, write text to a file, and read it back using only standard C++ libraries. The std::filesystem namespace is used to manage paths and directories, making the code portable across platforms. By avoiding platform-specific calls, you ensure that your application behaves consistently on Windows, macOS, and Linux. std::fstream provides a simple interface for file input and output, further supporting portability. Together, these libraries allow you to perform file and directory operations without worrying about the underlying operating system, making your C++ applications truly cross-platform.
¡Gracias por tus comentarios!
Pregunte a AI
Pregunte a AI
Pregunte lo que quiera o pruebe una de las preguntas sugeridas para comenzar nuestra charla