WRITE()
This is used to write binary or raw data to a file, as opposed to formatted output done using the <<
operator. The write()
function takes two arguments: a pointer to a character array (usually cast as const char*
) and a size value of type streamsize
that indicates how many bytes to write. Its typical use case is for writing data structures, binary files, or blocks of memory directly to a file. For example, file.write(reinterpret_cast<const char*>(&data), sizeof(data));
writes the raw bytes of the data
object to the file. Because it doesn't interpret the data as text, write()
is suitable for non-text file operations where exact byte representation matters. It's important to ensure the file is open and ready for output before calling write()
, and to handle any errors appropriately using file state checks like .fail()
or .good()
.
std::ostream& write(const char* s, std::streamsize n);
* s: Pointer to the block of memory (typically a char array) to write.
* n: Number of bytes to write from the memory block.
// Writing to a file using ofstream
#include <iostream> // For standard I/O operations
#include <fstream> // For file stream classes
using namespace std;
int main()
{
// Create an ofstream (output file stream) object and open the file
// Note: Use double backslashes in Windows file paths to escape them properly
ofstream write("C:\\Users\\Creator\\fileName.txt");
// Check if the file was successfully opened
if (!write) {
cerr << "Failed to open the file." << endl;
return 1; // Exit with an error code
}
// Write a line of text to the file
write << "Lorem ipsum dolor sit amet,...";
// Close the file to ensure data is saved and resources are released
write.close();
// Return 0 to indicate successful execution
return 0;
}
Last updated