Checking if two FILE *s are associated with the same stream.

Discussion in 'C Programming' started by Edd, May 23, 2004.

  1. Edd

    Edd Guest


    I have an array of strings containing filenames. I must open each in turn
    and parse the data within. However, if a filename appears multiple times in
    the list it must still only be read and parsed once.

    Initially, to solve this problem I thought strcmp'ing the filenames would
    suffice to check for duplicates in the list. However, it may be the case
    that "" identifies the same file as "~/inputs/",
    despite the strings being different. Thus simply using strcmp is inadequate.


    FILE *fptr1 = fopen("", "rb");
    FILE *fptr2 = fopen("~/inputs/", "rb");

    both return non-NULL, is there a portable way of checking that fptr1 and
    fptr2 are associated with the same stream?
    As a really nasty hack, I could check equality of the appropriate fields in
    the FILEs. But that probably wouldn't port outside of a given implementation
    of the standard library, let alone across Operating Systems.

    Can anybody suggest a way around my problem?

    Edd, May 23, 2004
    1. Advertisements

  2. No, not in ISO C. But many operating systems provide an OS specific
    way to check this, so you could ask in a group dedicated to your OS
    (e.g. comp.unix.programmer if you're writing code for Unix).
    I'd recommend to adhere to some standard that provides a way to achieve
    what you want (e.g. POSIX if you're writing code for Unix) instead of
    relying on implementation internals.

    Martin Dickopp, May 23, 2004
    1. Advertisements

  3. Edd

    Stephen L. Guest

    Check out (in support of Martin's post) ->

    Stephen L., May 23, 2004
  4. Edd

    Edd Guest

    [ 8< - - - snip ]
    Ah, that's pretty handy! I'll probably be coding my project in a *nix
    environment, but I'd like it to work on windows too. The code found at the
    end of the link you posted should make things considerably easier -- thanks!

    Edd, May 24, 2004
  5. [...]

    The C standard says very little about what file names are legal or how
    they map to external files. In particular, the C standard doesn't say
    anything about how the '~' and '/' characters in


    might be interpreted (or the '.' character, for that matter).

    If you're expecting '~' to have some particular special meaning, you
    should be sure that that meaning applies to an fopen() call.

    <OT>In Unix, it doesn't; if you have any questions about that, try
    Keith Thompson, May 25, 2004
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.