ch8-lseek (Read/write file, low level)
Chapter_8 Exercise_8-1 | Exercises_8-2,3 |
lseek.c K&R, p. 174-175 download
#include <stdio.h> // for BUFSIZ,, fprintf(), vfprintf(), stderr,
// SEEK_SET (0), SEEK_CUR (1), SEEK_END (2)
#include <stdlib.h> // for exit()
#include <fcntl.h> // for open(), creat()
#include <unistd.h> // for read(), write(), lseek(), unlink(), stdout (1)
#define PERM 0666 // RW for owner, group, others
void error(char *, ...);
// read n bytes from position pos, return no of bytes read
int get (int fd, long pos, char *buf, int n);
int main(int argc, char *argv[]) // read/write a file at random position
{
char buf[BUFSIZ]; // 8192 bytes
int fd, n;
if ((fd = creat("test.txt", PERM)) == -1)
{error("%s: can't create \"test.txt\", mode %03o", argv[0], PERM);}
if (write(fd, "Hello!\n", 7) != 7) // write
{error("%s: write error on file \"test.txt\"", argv[0]);}
lseek(fd, 0, SEEK_SET); // offset 0 from the beginning of file
if (write(fd, "Hello, ", 7) != 7) // overwrite
{error("%s: write error on file \"test.txt\"", argv[0]);}
// lseek(fd, 7, SEEK_SET); // offset 7 from the beginning of file
// lseek(fd, 0, SEEK_CUR); // offset 0 from the current position
// lseek(fd, 0, SEEK_END); // offset 0 from the end of file
if (write(fd, "world!\n", 7) != 7) // append
{error("%s: write error on file \"test.txt\"", argv[0]);}
close(fd);
if ((fd = open("test.txt", O_RDONLY, 0)) == -1) // 0 - permissions
{error("%s: can't open \"test.txt\"", argv[0]);}
if (get(fd, 0, buf, 7) == 7) // get first 7 chars (bytes)
{write(1, buf, 7);} // write to stdout (1)
if (get(fd, 7, buf, 7) == 7) // get more 7 chars (bytes)
{write(1, buf, 7);} // write to stdout (1)
close(fd);
unlink("test.txt"); // remove (delete) file
exit(0);
}
// read n bytes from position pos, return no of bytes read
int get (int fd, long pos, char *buf, int n)
{
if (lseek(fd, pos, SEEK_SET) >= 0)
{return read(fd, buf, n);}
// else
return -1;
}
#include <stdarg.h> // for va_list, va_start, va_end
// print an error message and die (end program)
void error(char *fmt, ...)
{
va_list args;
va_start(args, fmt);
fprintf(stderr, "Error: ");
vfprintf(stderr, fmt, args);
fprintf(stderr, "\n");
va_end(args);
exit(1); // end program from outside main()
}
/*
gcc lseek.c -o lseek
./lseek
Hello, world!
*/
Chapter_8 Exercise_8-1 | BACK_TO_TOP | Exercises_8-2,3 |
Comments
Post a Comment