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

下面我将提供一个简单的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 函数释放了动态分配的内存。

相关推荐
Giser探索家4 小时前
无人机桥梁巡检:以“空天地”智慧之力守护交通生命线
大数据·人工智能·算法·安全·架构·无人机
budingxiaomoli7 小时前
算法--滑动窗口(二)
算法
ID_180079054737 小时前
淘宝实时拍立淘按图搜索数据|商品详情|数据分析提取教程
算法·数据分析·图搜索算法
l1t7 小时前
Lua与LuaJIT的安装与使用
算法·junit·单元测试·lua·luajit
极客智造8 小时前
线性数据结构深度解析:数组、链表、栈与队列的实现与应用
数据结构·链表
Emilia486.9 小时前
【Leetcode&nowcode】代码强化练习(二叉树)
算法·leetcode·职场和发展
墨染点香9 小时前
LeetCode 刷题【135. 分发糖果】
算法·leetcode·职场和发展
Zhu_S W9 小时前
Redis跳表:高效有序数据结构的深度剖析
数据结构·数据库·redis
秋风战士9 小时前
通信算法之336 :3GPPMixed Mode Turbo Decoder
算法·matlab·fpga开发·信息与通信·基带工程
是那盏灯塔9 小时前
【算法】——动态规划之01背包问题
数据结构·c++·算法·动态规划