C++のfwrite関数の使い方は何ですか。

C++において、fwrite関数はデータブロックをファイルに書き込むために使用されます。その宣言は以下の通りです:

size_t fwrite(const void* ptr, size_t size, size_t count, FILE* stream);

ptrは書き込むデータブロックを指すポインタであり、sizeは1つのデータブロックのバイト数、countは書き込むデータブロックの数、streamは書き込み先ファイルを指すファイルポインタです。

fwrite関数は、ファイルストリームにsize*countバイトのデータを書き込み、実際に書き込まれたデータブロック数を返します。

サンプルコード:

#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;
}

この例では、data.txtファイルを開いて、”Hello, World!”という文字列をファイルに書き込み、そしてファイルを閉じます。

bannerAds