从给定的文件(例如input.txt)中读取第n个备用字节,并借助“ lseek”将其写入另一个文件中。
lseek(C系统调用) :lseek是一个系统调用,用于更改文件描述符的读/写指针的位置。可以以绝对或相对方式设置位置。
函数定义
off_t lseek(int fildes, off_t offset, int whence);
Field Description
int fildes : The file descriptor of the pointer that is going to be moved
off_t offset : The offset of the pointer (measured in bytes).
int whence : The method in which the offset is to be interpreted
(rela, absolute, etc.). Legal value r this variable are provided at the end.
return value : Returns the offset of the pointer (in bytes) from the
beginning of the file. If the return value is -1,
then there was an error moving the pointer.
例如,说我们的输入文件如下:
// C program to read nth byte of a file and
// copy it to another file using lseek
#include
#include
#include
#include
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;
}
输出文件(end.txt)