What is the usage of the fwrite function in C++?
In C++, the fwrite function is used to write data blocks to a file. Its declaration is as follows:
size_t fwrite(const void* ptr, size_t size, size_t count, FILE* stream);
ptr is a pointer to the data block to be written, size is the number of bytes in each data block, count is the number of data blocks to be written, and stream is a pointer to the file to be written to.
The fwrite function writes size*count bytes of data to the file stream and returns the actual number of data blocks written.
Example code:
#include <iostream>
#include <cstdio>
int main() {
FILE* file = fopen("data.txt", "wb"); // 以二进制写入模式打开文件
if (file == nullptr) {
std::cout << "Failed to open file." << std::endl;
return 1;
}
const char* data = "Hello, World!";
size_t size = sizeof(char);
size_t count = strlen(data);
size_t written = fwrite(data, size, count, file);
if (written != count) {
std::cout << "Error writing to file." << std::endl;
} else {
std::cout << "Data written to file successfully." << std::endl;
}
fclose(file); // 关闭文件
return 0;
}
In this example, we open a file named data.txt, write the string “Hello, World!” to the file, and then close the file.