在“lseek”的帮助下,从给定文件(例如 input.txt)中读取备用第 n 个字节并将其写入另一个文件。
lseek(C 系统调用):lseek 是一个系统调用,用于更改文件描述符的读/写指针的位置。位置可以以绝对或相对方式设置。
功能定义
off_t lseek(int fildes, off_t offset, int wherece);
字段说明
int fildes :将要移动的指针的文件描述符
off_t offset :指针的偏移量(以字节为单位)。
int whence :解释偏移量的方法(rela、absolute 等)。最后提供此变量的合法值 r。返回值:返回指针从文件开头的偏移量(以字节为单位) 。如果返回值为 -1,则移动指针时出错。
例如,假设我们的 Input 文件如下:
输出文件(end.txt)
// C program to read nth byte of a file and
// copy it to another file using lseek
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <fcntl.h>
void func(char arr[], int n)
{
// Open the file for READ only.
int f_write = open("start.txt", O_RDONLY);
// Open the file for WRITE and READ only.
int f_read = open("end.txt", O_WRONLY);
int count = 0;
while (read(f_write, arr, 1))
{
// to write the 1st byte of the input file in
// the output file
if (count < n)
{
// SEEK_CUR specifies that
// the offset provided is relative to the
// current file position
lseek (f_write, n, SEEK_CUR);
write (f_read, arr, 1);
count = n;
}
// After the nth byte (now taking the alternate
// nth byte)
else
{
count = (2*n);
lseek(f_write, count, SEEK_CUR);
write(f_read, arr, 1);
}
}
close(f_write);
close(f_read);
}
// Driver code
int main()
{
char arr[100];
int n;
n = 5;
// Calling for the function
func(arr, n);
return 0;
}