getenv function

This is a discussion on getenv function within the C Programming forums, part of the General Programming Boards category; Ok I hope some one can help! This is so frustrating because it should be real simple but it's not! ...

  1. #1
    Unregistered
    Guest

    Unhappy getenv function

    Ok I hope some one can help!
    This is so frustrating because it should be real simple but it's not!

    I'm programming in C on a Unix server. And what I'm trying to do is open a file for reading. I know the name of the file but it's directory is a Unix environment variable.

    For example: file abc.txt is in HOME
    so I need a way to ifp = fopen(???????, "r");

    Does anyone know of a way to use the getenv function to get the value of HOME and then somehow append abc.txt onto it so that I can get a nice directory/filename all in one?

  2. #2
    B26354 Deckard's Avatar
    Join Date
    Jan 2002
    Posts
    633
    Code:
    FILE *fptr;
    char path[PATH_MAX]; /* defined in limits.h */
    char *fname = "abc.txt"; /* or whatever the filename is */
    
    snprintf( path, PATH_MAX, "%s/%s", getenv("HOME"), fname );
    
    fptr = fopen( path, "r" );
    if ( !fptr )
    {
      ...
    }
    This should get you on track. A problem would occur if the home directory was set to "/", as root's sometimes is. It would be a good idea to test for that condition and change the snprintf() accordingly.
    Jason Deckard

  3. #3
    Unregistered
    Guest

    Talking

    Ok Thanks!
    I'll try it.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Seg Fault in Compare Function
    By tytelizgal in forum C Programming
    Replies: 1
    Last Post: 10-25-2008, 04:06 PM
  2. Another syntax error
    By caldeira in forum C Programming
    Replies: 31
    Last Post: 09-05-2008, 02:01 AM
  3. In over my head
    By Shelnutt2 in forum C Programming
    Replies: 1
    Last Post: 07-08-2008, 07:54 PM
  4. Including lib in a lib
    By bibiteinfo in forum C++ Programming
    Replies: 0
    Last Post: 02-07-2006, 02:28 PM
  5. Question..
    By pode in forum Windows Programming
    Replies: 12
    Last Post: 12-19-2004, 07:05 PM

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