#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>

/* by chatgpt */

int main() {
	const char* file_path = "example.txt";
	int file_descriptor;

	// Open the file for reading and writing
	file_descriptor = open(file_path, O_RDWR);
	if (file_descriptor == -1) {
		perror("Failed to open the file");
		return 1;
	}

	// Define a structure for the lock
	struct flock lock;
	memset(&lock, 0, sizeof(lock));

	lock.l_type = F_WRLCK; // Write (exclusive) lock
	lock.l_whence = SEEK_SET; // Start of file
	lock.l_start = 0; // Start from the beginning of the file
	lock.l_len = 0; // Lock the entire file

	// Try to acquire the lock
	if (fcntl(file_descriptor, F_SETLK, &lock) == -1) {
		perror("Failed to acquire lock");
		close(file_descriptor);
		return 1;
	}

	// Successfully acquired the lock, perform operations on the file
	printf("Lock acquired. Performing operations on the file...\n");

	// Read from the file
	char buffer[1024];
	ssize_t bytes_read = read(file_descriptor, buffer, sizeof(buffer));
	if (bytes_read == -1) {
		perror("Failed to read from the file");
	} else {
		printf("File contents:\n");
		write(STDOUT_FILENO, buffer, bytes_read);
	}

	// Write to the file
	const char* new_data = "This is a new line.";
	ssize_t bytes_written = write(file_descriptor, new_data, strlen(new_data));
	if (bytes_written == -1) {
		perror("Failed to write to the file");
	} else {
		printf("Data written to the file: %s\n", new_data);
	}

	// Release the lock
	lock.l_type = F_UNLCK;
	if (fcntl(file_descriptor, F_SETLK, &lock) == -1) {
		perror("Failed to release lock");
	} else {
		printf("Lock released.\n");
	}

	// Close the file
	close(file_descriptor);

	return 0;
}
