c++ write to file in directory
#include <iostream>
#include <fstream>
int main() {
std::ofstream file;
file.open("path/to/your/directory/filename.txt");
if (file.is_open()) {
file << "This is a line written to the file.";
file.close();
std::cout << "File written successfully." << std::endl;
} else {
std::cout << "Unable to open the file." << std::endl;
}
return 0;
}
Explanation:
#include <iostream>
and#include <fstream>
: These lines include necessary libraries for input/output operations and file handling in C++.std::ofstream file;
: This line declares an object namedfile
of typeofstream
which is used for writing to files.file.open("path/to/your/directory/filename.txt");
: Opens a file named "filename.txt" in the specified directory for writing. Replace"path/to/your/directory/filename.txt"
with the actual path and filename where you want to create/write the file.if (file.is_open()) { ... } else { ... }
: Checks if the file was successfully opened. If the file is open, it proceeds to write content to the file; otherwise, it prints an error message.file << "This is a line written to the file.";
: Writes the string"This is a line written to the file."
to the opened file.file.close();
: Closes the file after writing the content.std::cout << "File written successfully." << std::endl;
: If the file was successfully written, this line prints a success message to the console.return 0;
: Indicates successful execution of the program.