file - exceptions

Discussion in 'C' started by heidik, Oct 26, 2010.

  1. heidik

    heidik New Member

    Joined:
    Oct 23, 2010
    Messages:
    69
    Likes Received:
    0
    Trophy Points:
    0
    Could somebody please tell me how do I write a file in "try catch" block for checking if the file exists, if it is opened, if it is not empty. This is the error message I get when the file not exist or it is empty.

    Code:
    terminate called after throwing an instance of 'std::out_of_range'
      what():  basic_string::substr
    
     
  2. heidik

    heidik New Member

    Joined:
    Oct 23, 2010
    Messages:
    69
    Likes Received:
    0
    Trophy Points:
    0
    Could somebody please tell me how do I write a file in "try catch" block for checking if the file exists, if it is opened, if it is not empty. This is the error message I get when the file not exist or it is empty.

    Code:
    terminate called after throwing an instance of 'std::out_of_range'
      what():  basic_string::substr
    
     
  3. shifoo

    shifoo New Member

    Joined:
    Nov 1, 2010
    Messages:
    1
    Likes Received:
    0
    Trophy Points:
    0
    - Checking if file exists [You can use _access to check]

    #include <io.h>

    if(_access(“C:\\directory\\filename.txt”, 0) == -1)
    {
    //File does not exist
    }

    - Checking if file is opened

    You can use the normal way to open files and check if you can access and write to it. There is no way to tell if other processes have opened the file unless you check them. I think in linux you can check if the file is locked at that time.

    - Checking if file is empth [You can use peek() to check]

    First you open the file, then you use peek() from iostream to check if it returns eof. If so then the file is empty

    UAT Student
     

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice