0

I want to implement a function that gets as parameter a FILE*, that is already open in write mode (a, a+, w, w+ etc), and reads the contents of that file. The problem here is that the file is already locked (because of the fopen) and I need to close it before starting reading. However, after I have read the file I need to reopen it just like it was before my function was called.

Thus, I need both the file name and the mode the fopen was called with, initially.

I was able to get the file name. However the mode seems to be tricky. Since now I was able to get the mode code using the code below.

int fd = fileno(file_pointer);
int mode = fcntl(fd, F_GETFL);

Unfortunately, there is inconsistency among systems (same open mode -> different mode codes). Is the method shown above an actual way to get the mode a file was open in? Do you have any other ideas?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
  • 1
    It would be simpler to not modify the FILE* argument and open a second time the file in read mode. – user803422 Mar 16 '19 at 20:04
  • 1
    Why not just flush the file, then open it separately for reading? Why do you need to close it? – hyde Mar 16 '19 at 20:06
  • 1
    Why not open the file in a read/write mode in the first place? Then you can use `ftell` and `fseek` to restore the original condition. – Weather Vane Mar 16 '19 at 20:11
  • 2
    Note that if the file stream is opened in plain `"w"` mode or `"a"` mode, you won't be able to read it using that file stream. Also note that on Unix-like systems, `fopen()` does not lock the file — any file can be opened many times. Using `fcntl()` is about as good as it gets. – Jonathan Leffler Mar 16 '19 at 20:18
  • You might find useful information at [What's the expected behavior of `open(name, O_CREAT|O_DIRECTORY, mode)`?](https://stackoverflow.com/questions/45818628) It's more about file descriptors than file streams, but you're already looking at descriptors via `fileno()`. Remember, Unix does not distinguish between binary and text mode. Are you working on a Windows platform? The rules there may be different, and it does distinguish between binary and text mode. – Jonathan Leffler Mar 16 '19 at 20:19
  • You are right! The problem is that the string is not saved in the file instantly when fwrite is called rather than when the file is closed. – konstantinosAR Mar 16 '19 at 20:46

0 Answers0