文件内容分割,如有文件test.txt将文件内容平分并分别存储在两个文件test1.txt,test2,txt中(提示:参考平常上机给出cp类似功能代码,可能需要用到 lseek函数或stat函数)
2条回答 默认 最新
- ShowMeAI 2022-12-29 10:57关注
下面是一个用于文件内容分割的程序代码,它可以将文件test.txt中的内容平分并分别存储在两个文件test1.txt和test2.txt中。
- 首先,我们使用fopen函数打开test.txt文件,然后使用fstat函数获取文件大小。
- 然后我们使用lseek函数将文件指针移动到文件的一半处,这样我们就可以将文件内容分成两半了。
- 接着,我们使用fopen函数打开两个新文件test1.txt和test2.txt,然后使用fread函数从原文件中读取数据并写入新文件中。
- 最后,我们使用fclose函数关闭文件。
#include<stdio.h> #include<sys/types.h> #include<sys/stat.h> #include<fcntl.h> #include<unistd.h> int main() { //打开原文件test.txt int fd1 = open("test.txt", O_RDONLY); if (fd1 == -1) { perror("open test.txt failed"); return -1; } //获取原文件大小 struct stat st; int ret = fstat(fd1, &st); if (ret == -1) { perror("fstat failed"); return -1; } off_t file_size = st.st_size; //将文件指针移动到文件的一半处 off_t pos = lseek(fd1, file_size / 2, SEEK_SET); if (pos == -1) { perror("lseek failed"); return -1; } //打开新文件test1.txt int fd2 = open("test1.txt", O_CREAT | O_WRONLY, 0644); if (fd2 == -1) { perror("open test1.txt failed"); return -1; } //将文件指针移动到文件的开头处 ret = lseek(fd1, 0, SEEK_SET); if (ret == -1) { perror("lseek failed"); return -1; } //读取原文件的前一半内容并写入新文件test1.txt char buf[1024]; int n; while ((n = read(fd1, buf, sizeof(buf))) > 0) { write(fd2, buf, n); } //关闭文件test1.txt close(fd2); //打开新文件test2.txt int fd3 = open("test2.txt", O_CREAT | O_WRONLY, 0644); if (fd3 == -1) { perror("open test2.txt failed"); return -1; } //打开新文件test2.txt int fd3 = open("test2.txt", O_CREAT | O_WRONLY, 0644); if (fd3 == -1) { perror("open test2.txt failed"); return -1; } //读取原文件的后一半内容并写入新文件test2.txt while ((n = read(fd1, buf, sizeof(buf))) > 0) { write(fd3, buf, n); } //关闭文件test2.txt close(fd3); //关闭原文件test.txt close(fd1); return 0; }
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 1无用
悬赏问题
- ¥15 Oracle中如何从clob类型截取特定字符串后面的字符
- ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
- ¥15 MATLAB中streamslice问题
- ¥15 如何在炒股软件中,爬到我想看的日k线
- ¥15 51单片机中C语言怎么做到下面类似的功能的函数(相关搜索:c语言)
- ¥15 seatunnel 怎么配置Elasticsearch
- ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
- ¥15 (标签-MATLAB|关键词-多址)
- ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
- ¥500 52810做蓝牙接受端