文件内容分割程序代码

文件内容分割,如有文件test.txt将文件内容平分并分别存储在两个文件test1.txt,test2,txt中(提示:参考平常上机给出cp类似功能代码,可能需要用到 lseek函数或stat函数)

下面是一个用于文件内容分割的程序代码,它可以将文件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;
}

读取文件大小,根据大小分配文件内容进行读写操作