如何实现一个函数,用于将整数数组写入文件,并从文件中读取整数数组

下面我将提供一个简单的C语言示例,展示了如何实现一个函数将整数数组写入文件,以及另一个函数从文件中读取整数数组。为了简化,我们将假设整数数组的长度是已知的,并且在写入文件之前已经定义好了。

写入整数数组到文件

复制代码

c复制代码

|---|------------------------------------------------------------------------------------|
| | #include <stdio.h> |
| | #include <stdlib.h> |
| | |
| | // 写入整数数组到文件 |
| | void writeIntArrayToFile(const int* array, size_t size, const char* filename) { |
| | FILE* file = fopen(filename, "wb"); // 以二进制写入模式打开文件 |
| | if (file == NULL) { |
| | perror("打开文件失败"); |
| | exit(EXIT_FAILURE); |
| | } |
| | |
| | // 写入数组的大小(可选,用于读取时知道要读取多少元素) |
| | fwrite(&size, sizeof(size_t), 1, file); |
| | |
| | // 写入数组内容 |
| | fwrite(array, sizeof(int), size, file); |
| | |
| | fclose(file); |
| | } |
| | |
| | ### 读取整数数组从文件 |
| | |
| | c ```` | | | `// 从文件中读取整数数组 ` | | | `int* readIntArrayFromFile(const char* filename, size_t* size) { ` | | | `FILE* file = fopen(filename, "rb"); // 以二进制读取模式打开文件 ` | | | `if (file == NULL) { ` | | | `perror("打开文件失败"); ` | | | `return NULL; ` | | | `} ` | | | | | | `// 读取数组的大小 ` | | | `if (fread(size, sizeof(size_t), 1, file) != 1) { ` | | | `perror("读取数组大小失败"); ` | | | `fclose(file); ` | | | `return NULL; ` | | | `} ` | | | | | | `// 分配内存来存储数组 ` | | | `int* array = (int*)malloc(*size * sizeof(int)); ` | | | `if (array == NULL) { ` | | | `perror("内存分配失败"); ` | | | `fclose(file); ` | | | `return NULL; ` | | | `} ` | | | | | | `// 读取数组内容 ` | | | `if (fread(array, sizeof(int), *size, file) != *size) { ` | | | `perror("读取数组内容失败"); ` | | | `free(array); ` | | | `fclose(file); ` | | | `return NULL; ` | | | `} ` | | | | | | `fclose(file); ` | | | `return array; ` | | | `} ` | | | | | | `### 示例用法 ` | | | | | | c ```` |
| | int main() { |
| | // 示例整数数组 |
| | int numbers[] = {1, 2, 3, 4, 5}; |
| | size_t size = sizeof(numbers) / sizeof(numbers[0]); |
| | |
| | // 写入数组到文件 |
| | writeIntArrayToFile(numbers, size, "numbers.bin"); |
| | |
| | // 从文件读取数组 |
| | size_t readSize; |
| | int* readNumbers = readIntArrayFromFile("numbers.bin", &readSize); |
| | if (readNumbers != NULL) { |
| | // 输出读取的数组内容 |
| | for (size_t i = 0; i < readSize; ++i) { |
| | printf("%d ", readNumbers[i]); |
| | } |
| | printf("\n"); |
| | |
| | // 释放分配的内存 |
| | free(readNumbers); |
| | } |
| | |
| | return 0; |
| | } |

注意:在这个示例中,我们使用了二进制模式("wb""rb")来打开文件,这样可以确保整数以它们在内存中的原始格式写入和读取,而不受文本模式可能引入的换行符转换等问题的影响。另外,我们还写入了数组的大小到文件中,这样读取时就能知道要读取多少元素。在读取完成后,我们使用 free 函数释放了动态分配的内存。

相关推荐
刺客-Andy37 分钟前
前端加密方式 AES对称加密 RSA非对称加密 以及 MD5哈希算法详解
前端·javascript·算法·哈希算法
记得早睡~1 小时前
leetcode122-买卖股票的最佳时机II
javascript·数据结构·算法·leetcode
黄油烤菠萝1 小时前
蓝桥杯-卡java排序
c++·算法·蓝桥杯
不要天天开心1 小时前
Scala集合
图像处理·算法·机器学习·scala
uhakadotcom1 小时前
Google Cloud Dataproc:简化大数据处理的强大工具
后端·算法·面试
uhakadotcom2 小时前
PyTorch 分布式训练入门指南
算法·面试·github
uhakadotcom2 小时前
PyTorch 与 Amazon SageMaker 配合使用:基础知识与实践
算法·面试·github
Craaaayon2 小时前
Java八股文-List集合
java·开发语言·数据结构·list
uhakadotcom2 小时前
在Google Cloud上使用PyTorch:如何在Vertex AI上训练和调优PyTorch模型
算法·面试·github
wen__xvn2 小时前
c++STL入门
开发语言·c++·算法