fread() 是一个C语言中的文件处理函数,用于从文件流中读取数据
fopen() 函数,传入文件名和打开模式(例如 “r” 表示只读模式)。FILE *file = fopen("example.txt", "r"); if (file == NULL) { printf("Error opening file."); return 1; } int n_elements = 100; // 假设我们要读取100个整数 size_t element_size = sizeof(int); int *buffer = (int *) malloc(n_elements * element_size); if (buffer == NULL) { printf("Memory allocation failed."); fclose(file); return 1; } fread() 函数从文件中读取数据。将文件指针、缓冲区指针、元素大小和元素数量作为参数传递。size_t bytes_read = fread(buffer, element_size, n_elements, file); if (bytes_read != n_elements) { printf("Error reading file. Read %zu elements instead of %d.", bytes_read, n_elements); free(buffer); fclose(file); return 1; } for (size_t i = 0; i< bytes_read; ++i) { printf("%d ", buffer[i]); } printf("\n"); fclose(file); free(buffer); 这就是如何结合其他文件处理函数使用 fread() 的基本方法。请注意,这个示例假设文件中的数据是整数类型。如果你要处理不同类型的数据,需要相应地调整代码。