fwrite demo
时间: 2023-10-01 16:04:24 浏览: 46
Sure, here is a simple demonstration of using the `fwrite` function in C:
```c
#include <stdio.h>
int main() {
FILE *fp;
char data[] = "Hello, CSDN!";
// Open file for writing
fp = fopen("output.txt", "w");
if (fp == NULL) {
printf("Failed to open file.\n");
return 1;
}
// Write data to file
fwrite(data, sizeof(char), sizeof(data) - 1, fp);
// Close file
fclose(fp);
printf("Data written to file.\n");
return 0;
}
```
In this example, we include the `stdio.h` library for file I/O operations. We declare a file pointer `fp` and a character array `data` containing the string we want to write to the file.
We open a file named "output.txt" in write mode using `fopen`. If the file fails to open, an error message is printed and the program returns. Otherwise, we use `fwrite` to write the contents of the `data` array to the file.
After writing the data, we close the file using `fclose`. Finally, a success message is printed.