Funny error in fopen

This is a discussion on Funny error in fopen within the C++ Programming forums, part of the General Programming Boards category; I have a code Code: FILE *opfile = fopen("output.txt", "w"); and this code is in a function which is called ...

  1. #1
    Registered User
    Join Date
    Dec 2004
    Posts
    163

    Funny error in fopen

    I have a code
    Code:
    FILE *opfile = fopen("output.txt", "w");
    and this code is in a function which is called more than hundred of times.

    And sometimes opfile == NULL, which I think is unbelievable. How can writing to a file generates an error? Does anyone encounter this problem before?

    Thanks alot for your help.

  2. #2
    Deathray Engineer MacGyver's Avatar
    Join Date
    Mar 2007
    Posts
    3,211
    fopen() returns NULL if the file can't be opened. There are plenty of reasons why a file can't be opened. This check is necessary.

  3. #3
    Registered User
    Join Date
    Dec 2004
    Posts
    163
    What could be the reasons? Is it possible that there is memory corruption in my program? Or is it some applications is using result.txt?

  4. #4
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,659
    Well if you're opening it "more than hundred of times", then my guess is you're not closing the file later on, and you've run out of file handles.

    You could do this,
    Code:
    FILE *opfile = fopen("output.txt", "w");
    if ( opfile == NULL ) {
      perror("This is how it goes");
    }
    and see exactly why the file could not be opened.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

  5. #5
    Registered User
    Join Date
    Dec 2004
    Posts
    163
    oh man, you are GOOD! you are spot on. I think I run out of file handles. Somewhere in my program, I didn't close another file pointer and all these file pointers accumulate.

    Thanks alot Salem and MacGyver

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. help with stat() and fopen()
    By movl0x1 in forum C Programming
    Replies: 6
    Last Post: 07-25-2007, 05:28 AM
  2. fopen help.
    By chriscolden in forum C Programming
    Replies: 17
    Last Post: 01-13-2006, 05:27 AM
  3. problem with fopen command
    By emon in forum C Programming
    Replies: 2
    Last Post: 03-11-2004, 11:11 PM
  4. fopen() and open()
    By Encrypted in forum C Programming
    Replies: 8
    Last Post: 02-09-2003, 03:57 PM
  5. fopen vs open
    By rotis23 in forum Linux Programming
    Replies: 5
    Last Post: 12-10-2002, 01:30 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21