Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Re-open file read-only in Linux (or POSIX) [duplicate]

Tags:

c

linux

posix

I open a file in read/write mode and do a series of reads, writes and seeks (from user input).

At some point later on I want to make the file read-only to prevent any further writes to it.

Is there a Linux (or POSIX) function to do that? Perhaps some fcntl call?

Or is my only option is to save the current position in the file, close it and reopen RD_ONLY?

#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>

int fd = open("/path/to/file", O_RDWR);

// mixture of:
write(fd, ...);
lseek(fd, ...);
read (fd, ...);
// etc

...

// make file read-only ???

read (fd, ...); // OK
lseek(fd, ...); // OK
write(fd, ...); // error
like image 223
Innocent Bystander Avatar asked Aug 17 '17 02:08

Innocent Bystander


People also ask

Is Fcntl a Posix?

h is the header in the C POSIX library for the C programming language that contains constructs that refer to file control, e.g. opening a file, retrieving and changing the permissions of file, locking a file for edit, etc.

What is the Oflag used to open a file with the mode read only?

Applications must specify exactly one of the first three values (file access modes) below in the value of oflag: O_RDONLY. Open for reading only. O_WRONLY.


1 Answers

This is not possible at least through call to fcntl as the POSIX docs says (emphasis is mine):

fcntl():

F_SETFL

Set the file status flags, defined in fcntl.h, for the file description associated with fildes from the corresponding bits in the third argument, arg, taken as type int. Bits corresponding to the file access mode and the file creation flags, as defined in fcntl.h, that are set in arg shall be ignored. If any bits in arg other than those mentioned here are changed by the application, the result is unspecified.

and

fcntl.h

O_ACCMODE Mask for file access modes.

The header shall define the following symbolic constants for use as the file access modes for open(), openat(), and fcntl(). The values shall be unique, except that O_EXEC and O_SEARCH may have equal values. The values shall be suitable for use in #if preprocessing directives.

O_EXEC Open for execute only (non-directory files). The result is unspecified if this flag is applied to a directory.

O_RDONLY Open for reading only.

O_RDWR Open for reading and writing.

O_SEARCH Open directory for search only. The result is unspecified if this flag is applied to a non-directory file.

O_WRONLY Open for writing only.

like image 63
Jean-Baptiste Yunès Avatar answered Sep 21 '22 20:09

Jean-Baptiste Yunès