The Linux Programming Interface

(nextflipdebug5) #1

84 Chapter 4


Section 14.4 describes how holes are represented in a file, and Section 15.1
describes the stat() system call, which can tell us the current size of a file, as well as
the number of blocks actually allocated to the file.

Example program
Listing 4-3 demonstrates the use of lseek() in conjunction with read() and write().
The first command-line argument to this program is the name of a file to be
opened. The remaining arguments specify I/O operations to be performed on the
file. Each of these operations consists of a letter followed by an associated value
(with no separating space):

z soffset: Seek to byte offset from the start of the file.
z rlength: Read length bytes from the file, starting at the current file offset, and
display them in text form.
z Rlength: Read length bytes from the file, starting at the current file offset, and
display them in hexadecimal.
z wstr: Write the string of characters specified in str at the current file offset.

Listing 4-3: Demonstration of read(), write(), and lseek()
––––––––––––––––––––––––––––––––––––––––––––––––––––––––– fileio/seek_io.c
#include <sys/stat.h>
#include <fcntl.h>
#include <ctype.h>
#include "tlpi_hdr.h"

int
main(int argc, char *argv[])
{
size_t len;
off_t offset;
int fd, ap, j;
char *buf;
ssize_t numRead, numWritten;

if (argc < 3 || strcmp(argv[1], "--help") == 0)
usageErr("%s file {r<length>|R<length>|w<string>|s<offset>}...\n",
argv[0]);

fd = open(argv[1], O_RDWR | O_CREAT,
S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP |
S_IROTH | S_IWOTH); /* rw-rw-rw- */
if (fd == -1)
errExit("open");

for (ap = 2; ap < argc; ap++) {
switch (argv[ap][0]) {
case 'r': /* Display bytes at current offset, as text */
case 'R': /* Display bytes at current offset, in hex */
len = getLong(&argv[ap][1], GN_ANY_BASE, argv[ap]);
Free download pdf