How to use fwrite in C to write data to a file?

In C language, we can use the fwrite function to write data to a file. The prototype of the fwrite function is as follows:

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

Here, ptr is a pointer pointing to the data to be written, size is the size of each data item in bytes, nmemb is the number of data items to be written, and stream is a pointer to the file to be written to.

Here is an example demonstrating how to use fwrite to write data to a file.

#include <stdio.h>

int main() {
    FILE *fp;
    char data[] = "Hello, World!";

    // 打开文件以写入数据
    fp = fopen("output.txt", "wb");
    
    // 将数据写入文件
    fwrite(data, sizeof(char), sizeof(data), fp);
    
    // 关闭文件
    fclose(fp);

    return 0;
}

This code opens a file named output.txt and writes the string “Hello, World!” into the file. After writing data using the fwrite function, you need to call the fclose function to close the file.

 

More tutorials

What is the difference between fread and fwrite in C language?(Opens in a new browser tab)

convert string to character array in Java.(Opens in a new browser tab)

How to initialize a C language second-level pointer?(Opens in a new browser tab)

How to initialize a C language second-level pointer?(Opens in a new browser tab)

What is the purpose of a double pointer in the C language?(Opens in a new browser tab)

How to handle a large number of concurrent read and write requests in Cassandra?(Opens in a new browser tab)

Leave a Reply 0

Your email address will not be published. Required fields are marked *