/* fileops.c - file-system operations using system calls (BACSE106 Lab 15) */
#include <stdio.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>

int main(void)
{
    char buf[100];
    int fd, n;

    /* 1. create a file and write to it */
    fd = open("demo.txt", O_CREAT | O_WRONLY | O_TRUNC, 0644);
    if (fd < 0) { perror("open"); return 1; }
    write(fd, "Operating Systems\n", 18);
    write(fd, "File system calls\n", 18);
    close(fd);
    printf("Created demo.txt and wrote 36 bytes\n");

    /* 2. open it again and read everything */
    fd = open("demo.txt", O_RDONLY);
    n = read(fd, buf, sizeof(buf) - 1);
    buf[n] = '\0';
    printf("Read %d bytes:\n%s", n, buf);

    /* 3. reposition with lseek and read part of the file */
    lseek(fd, 10, SEEK_SET);                 /* jump to byte 10 */
    n = read(fd, buf, 7);
    buf[n] = '\0';
    printf("After lseek(fd, 10, SEEK_SET), read 7 bytes: \"%s\"\n", buf);
    printf("File size using lseek(fd, 0, SEEK_END) = %ld bytes\n", (long)lseek(fd, 0, SEEK_END));
    close(fd);

    /* 4. append to the file */
    fd = open("demo.txt", O_WRONLY | O_APPEND);
    write(fd, "Appended line\n", 14);
    close(fd);
    printf("Appended 14 bytes\n");

    /* 5. copy demo.txt to copy.txt block by block */
    int in = open("demo.txt", O_RDONLY);
    int out = open("copy.txt", O_CREAT | O_WRONLY | O_TRUNC, 0644);
    while ((n = read(in, buf, sizeof(buf))) > 0)
        write(out, buf, n);
    close(in);
    close(out);
    printf("Copied demo.txt to copy.txt\n");

    /* 6. delete the copy */
    if (unlink("copy.txt") == 0)
        printf("Deleted copy.txt\n");
    return 0;
}
