setbuf
函數用于設置 C 語言程序中某個文件流的緩沖區
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int setbuf(FILE *stream, char *buffer, size_t size);
int main() {
char *custom_buffer = (char *)malloc(1024);
if (custom_buffer == NULL) {
fprintf(stderr, "Memory allocation failed\n");
return 1;
}
FILE *file = fopen("example.txt", "w+");
if (file == NULL) {
fprintf(stderr, "Failed to open file\n");
free(custom_buffer);
return 1;
}
if (setbuf(file, custom_buffer, 1024) != 0) {
fprintf(stderr, "Failed to set buffer\n");
fclose(file);
free(custom_buffer);
return 1;
}
// Perform file operations here
fclose(file);
free(custom_buffer);
return 0;
}
在這個示例中,我們首先為自定義緩沖區分配了內存,然后使用 setbuf
函數將其設置為文件流的緩沖區。這樣,當我們對該文件進行讀寫操作時,數據將存儲在自定義緩沖區中。