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.