9

Is there any way to access the file descriptor of a file opened in c++? So ...

 #include <iostream>
 #include <fstream>
 using namespace std;

 int main() {
      ifstream inputFile( "file.txt",ios::in );
      cout << inputFile.fileDesc << endl;//made up call
      return 0;
 }

The question is, does something like fileDesc exist for ifstreams? If not how would I go about doing this?

Dan Snyder
  • 1,483
  • 7
  • 20
  • 29
  • The question is why do you want to do this? If you explain your rational then maybe an alternative can be found that solves your actual problem. – Martin York Aug 18 '10 at 14:58
  • The reason that I need the file descriptor is that I need to run fstat() on a file as some time after it has been opened. I realize that I could use stat() on the filename but I am using fstat() so I can get stats on streams as well. I just wanted a concise method that could be used for the reserved stream descriptors (0(STDIN), 1(STDOUT), and 2(STDERR) and for files that are opened. – Dan Snyder Aug 18 '10 at 15:14
  • EDIT: I realize that ifstream is a stream, but it doesn't have a reserved filedes like the previosly mentioned IO streams. – Dan Snyder Aug 18 '10 at 15:16
  • possible duplicate of [Getting a FILE* from a std::fstream](http://stackoverflow.com/questions/109449/getting-a-file-from-a-stdfstream) – outis Jul 19 '12 at 11:00
  • 2
    I want to get the file descriptor in Linux so I can [`flock()`](http://linux.die.net/man/2/flock) the file. – Craig McQueen Apr 06 '16 at 06:10

2 Answers2

5

If you're trying to get to the FILE* from the stream then the answer is basically "you can't" as stated by more enlightened people than me here.

Community
  • 1
  • 1
celavek
  • 5,575
  • 6
  • 41
  • 69
4

Take a look at open():

The open function creates and returns a new file descriptor for the file named by filename.

karlphillip
  • 92,053
  • 36
  • 243
  • 426