iseek() 函数在 C/C++ 中交替读取每第 n 个字节,并写入另一个文件中


在本教程中,我们将讨论一个程序,了解如何读取交替的第 n 个字节并将其写入另一个文件中。

为此,我们将提供两个 .txt 文件。我们的任务是使用 Iseek() 将一个文件中的内容写入另一个文件,Iseek() 用于更改文件描述符的指针。

示例

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <fcntl.h>
void func(char arr[], int n){
   int f_write = open("start.txt", O_RDONLY);
   int f_read = open("end.txt", O_WRONLY);
   int count = 0;
   while (read(f_write, arr, 1)){
      if (count < n) {
         lseek (f_write, n, SEEK_CUR);
         write (f_read, arr, 1);
         count = n;
      }
      else{
         count = (2*n);
         lseek(f_write, count, SEEK_CUR);
         write(f_read, arr, 1);
      }
   }
   close(f_write);
   close(f_read);
}
int main(){
   char arr[100];
   int n;
   n = 5;
   func(arr, n);
   return 0;
}

输出

(第一个文件)

(输出文件)

更新日期:2020 年 4 月 1 日

588 次查看

开启你的 职业

完成课程并获得认证

开始学习
广告
© . All rights reserved.