setbuf
函数用于设置 C 语言程序中某个文件流的缓冲区
#include#include #include 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
函数将其设置为文件流的缓冲区。这样,当我们对该文件进行读写操作时,数据将存储在自定义缓冲区中。