1

I am working on old C/C++ code someone in my company wrote for Linux. The code opens a file using fopen() and then locks the file using flock():

FILE *fp=fopen("text.txt", "wt");
flock( fp, LOCK_EX );

The problem is that when I compile the code using Eclipse on Linux, the compiler throws an error:

    invalid conversion from ‘FILE*’ {aka ‘_IO_FILE*’} to ‘int’

flock() obviously takes an int as the 1st parameter.

What function can I use to convert "FILE *" into int?

Tanktalus
  • 21,664
  • 5
  • 41
  • 68
yaronkl
  • 510
  • 2
  • 5
  • 18
  • Possible duplicate of [How do I lock files using fopen()?](https://stackoverflow.com/q/7573282/608639), [How to block file when you reading (fopen) it](https://stackoverflow.com/q/26313856/608639), [File locking in Linux using C program](https://stackoverflow.com/q/13468238/608639), etc. – jww Apr 01 '19 at 23:47
  • I don't understand how this could ever have worked; `flock` has taken an `int` (file descriptor) and not a `FILE *` for its entire history. – zwol Apr 02 '19 at 00:59
  • Beats me :-( the original code was in C, not C++, so perhaps the compiler used then (20 years ago) allowed it. – yaronkl Apr 02 '19 at 02:22
  • @yaronki There certainly have been C compilers that would _compile_ your sample fragment without complaint, but, at runtime, the file would not have been locked. Possibly the `flock` has always failed (setting `errno` to `EBADF`, I would expect) and nobody noticed. – zwol Apr 02 '19 at 16:43

1 Answers1

3

You'll want fileno(3):

flock( fileno(fp), LOCK_EX);
Tanktalus
  • 21,664
  • 5
  • 41
  • 68