csci3753

CSCI3753 Coursework
git clone https://git.pngu.org/csci3753
Log | Files | Refs | README

file_test.c (1792B)


// Authour: jasa7131
// CSCI3753 SP2024
// PA2 File Tester
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#define MAX_SIZE 256

int main(int argc, char **argv) {
  if (argc < 2) {
    printf("%s error: missing filename\n", argv[0]);
    exit(EXIT_FAILURE);
  }
  int fd = open(argv[1], O_RDWR);
  if (!fd) {
    printf("%s error: invalid filename\n", argv[0]);
    exit(EXIT_FAILURE);
  }
  char *read_data, write_data[MAX_SIZE], input;
  int bytes, offset, whence;
  printf("Option (r for read, w for write, s for seek): ");
  while (scanf("%c", &input) != EOF) {
    switch (input) {

    case 'r':
      printf("Enter the number of bytes you want to read: ");
      scanf("%d", &bytes);
      read_data = (char *)malloc(bytes * sizeof(char));
      if (read(fd, read_data, bytes) < 0) {
        fprintf(stderr, "%s error: read failed\n", argv[0]);
        free(read_data);
        exit(EXIT_FAILURE);
      }
      printf("%s\n", read_data);
      free(read_data);
      break;

    case 'w':
      printf("Enter the data you want to write: ");
      scanf(" %255[^\n]", write_data);
      int n = strlen(write_data) + 1;
      write_data[n] = '\0';
      if (write(fd, write_data, n) < 0) {
        fprintf(stderr, "%s error: write failed\n", argv[0]);
        exit(EXIT_FAILURE);
      }
      break;

    case 's':
      printf("Enter an offset value: ");
      scanf("%d", &offset);
      printf("Enter a value for whence: ");
      scanf("%d", &whence);
      if (lseek(fd, offset, whence) < 0) {
        fprintf(stderr, "%s error: seek failed\n", argv[0]);
        exit(EXIT_FAILURE);
      }
      break;

    default:
      printf("Option (r for read, w for write, s for seek): ");
    }
  }
  close(fd);
  return EXIT_SUCCESS;
}