fopen函数写入数组,并取出数组

写入数组并序列化

$filename="data.txt";
$file_hwnd=fopen($filename,"w");
fwrite($file_hwnd,serialize($arr)); //输入序列化的数据
fclose($file_hwnd);

取出数组

$filename="data.txt";
$file_hwnd=fopen($filename,"r");
$content = fread($file_hwnd, filesize($filename)); // 读去文件全部内容
fclose($file_hwnd);
$arr = unserialize($content);
$new_arr = unserialize($content); //反序列化操作

写入新的数组并覆盖

$myfile = fopen("data.txt", "w") or die("Unable to open file!");
fwrite($myfile, serialize($new_arr));//serialize因个人需要序列化操作
fclose($myfile);
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,这是一个关于文件读写的问题。以下是代码实现: ```c #include <stdio.h> #include <stdlib.h> // 定义员工结构体 struct employee { char name[20]; char sex[10]; float salary; }; int main() { int i; FILE *fp; // 定义员工数组 struct employee emps[5] = { {"Tom", "male", 3000.0}, {"Jerry", "female", 4000.0}, {"Alice", "male", 5000.0}, {"Bob", "female", 6000.0}, {"John", "male", 7000.0} }; // 将数组写入文件 fp = fopen("employee.dat", "wb"); if (fp == NULL) { printf("File open error!\n"); exit(1); } fwrite(emps, sizeof(struct employee), 5, fp); fclose(fp); // 从文件读取内容并显示 fp = fopen("employee.dat", "rb"); if (fp == NULL) { printf("File open error!\n"); exit(1); } for (i = 0; i < 5; i++) { fread(&emps[i], sizeof(struct employee), 1, fp); printf("%s\t%s\t%.2f\n", emps[i].name, emps[i].sex, emps[i].salary); } fclose(fp); return 0; } ``` 上述代码中,我们首先定义了一个 `struct employee` 结构体类型,包含了员工的姓名、性别和工资三个字段。接着,我们定义了一个 `emps` 数组,其中包含了 5 个员工的信息。然后,我们使用 `fwrite()` 函数将 `emps` 数组中的值写入到名为 `employee.dat` 的二进制文件中。接下来,我们使用 `fread()` 函数从 `employee.dat` 文件中读取出每个员工的信息,并在屏幕上显示出来。 需要注意的是,在使用 `fwrite()` 函数写入数据时,我们需要指定写入的数据大小为 `sizeof(struct employee)`,写入的数据个数为 5,即 `fwrite(emps, sizeof(struct employee), 5, fp)`。在使用 `fread()` 函数读取数据时,我们需要指定读取的数据大小为 `sizeof(struct employee)`,读取的数据个数为 1,即 `fread(&emps[i], sizeof(struct employee), 1, fp)`。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值