First Test whether the standard input can be lseek operation
[email protected] 03]# cat ex03-lseek-01.c
/* File ex03-lseek-01.c,
Use the Lseek function to test whether the standard input can be used for seek operations */
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
int main (void)
{
off_t offset =-1;
/* Set the file offset of the standard input file descriptor to the current value */
offset = Lseek (stdin, 0, seek_cur);
if ( -1 = = offset) {
/* Setup failed, standard input cannot be seek action */
printf ("STDIN can ' t seek\n");
return-1;
}else{
/* Setup succeeded, standard input can be used for seek operation */
printf ("STDIN CAN seek\n");
};
return 0;
}
[Email protected] 03]#./ex03-lseek-01
STDIN can ' t seek
----------------------------------------------------------------------------
[email protected] 03]# cat ex03-lseek-02.c
/* File ex03-lseek-02.c,
Using the Lseek function to build an empty file */
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
int main (void)
{
int FD = -1,i;
ssize_t size =-1;
off_t offset =-1;
/* buffer for storing data */
Char buf1[]= "01234567";
Char buf2[]= "ABCDEFGH";
/* File name */
Char filename[] = "Hole.txt";
int len = 8;
/* Create a file hole.txt*/
FD = open (filename,o_rdwr| O_CREAT,S_IRWXU);
if ( -1 = = FD) {
/* Failed to create file */
return-1;
}
/* Write data from buf1 to file Hole.txt */
Size = Write (fd, Buf1,len);
if (size! = Len) {
/* Failed to write data */
return-1;
}
/* Set the file offset to absolute 32*/
offset = Lseek (FD, +, seek_set);
if ( -1 = = offset) {
/* Setup failed */
return-1;
}
/* Write data from buf2 to file Hole.txt */
Size = Write (fd, Buf2,len);
if (size! = Len) {
/* Failed to write data */
return-1;
}
/* Close File */
Close (FD);
return 0;
}
[email protected] 03]# cat Hole.txt
01234567ABCDEFGH
[Email protected] 03]# od-c hole.txt #16进制工具od查看
0000000 0 1 2 3 4 5 6 7
0000020.,,, and so on.
0000040 A B C D E F G H
0000050