How do I use file locks on macOS in C++?

File locks in macOS can be implemented using the `fcntl` function, which allows you to apply advisory locks to files. This is useful for controlling access to files in concurrent programming to ensure that only one process can write to or read from a file at a time, avoiding data corruption.

This example demonstrates how to create a file lock using C++ on macOS:

#include <iostream> #include <fcntl.h> #include <cstdio> #include <unistd.h> int main() { const char* filename = "example.txt"; FILE* file = fopen(filename, "w"); if (!file) { perror("File opening failed"); return EXIT_FAILURE; } struct flock lock; lock.l_type = F_WRLCK; // Write lock lock.l_whence = SEEK_SET; // Lock starting from the beginning lock.l_start = 0; // Lock starts from byte 0 lock.l_len = 0; // Lock till the end of the file // Try to acquire the lock if (fcntl(fileno(file), F_SETLK, &lock) == -1) { perror("Failed to acquire lock"); fclose(file); return EXIT_FAILURE; } // Write to the file fprintf(file, "This file is locked for writing.\n"); // Release the lock lock.l_type = F_UNLCK; // Unlock fcntl(fileno(file), F_SETLK, &lock); fclose(file); return EXIT_SUCCESS; }

File locks macOS C++ advisory locks fcntl file access control