Thread: Strings

    #1
  1. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jun 2003
    Location
    Scotland
    Posts
    185
    Rep Power
    11

    Strings


    Hi all,

    I want to check that a speficic file exists in a directory before I begin my program.

    I wrote code to ask the user for the location of their files, this is stored in a variable.

    The file that is being looked at always has the same name, so I want to open the filename in the directory specifed. Opening a file is easy, but how can I join the variable with the the constant.

    eg, variable is c:\tesdir
    and the constant is \testfile.txt

    how can I create one variable with the contents

    c:\tesdir\testfile.txt
  2. #2
  3. *bounce*
    Devshed Novice (500 - 999 posts)

    Join Date
    Jan 2002
    Location
    Delft, The Netherlands
    Posts
    514
    Rep Power
    42
    If you're using C (as opposed to C++), you might do something like this:

    Code:
    char *dir = "C:\\tesdir";
    char *file = "\\testfile.txt";
    char *full_path;
    
    int len;
    
    len = strlen(dir) + strlen(file) + 1;
    if ( (full_path = malloc(len)) == NULL) {
        /* handle error and exit */
    }
    
    strcpy(full_path, dir);
    strcat(full_path, file);
    If you're using C++, there are better ways to do this (using the String class, I believe). But you'll have to ask someone else :)
    "A poor programmer is he who blames his tools."
    http://analyser.oli.tudelft.nl/
  4. #3
  5. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jun 2003
    Location
    Scotland
    Posts
    185
    Rep Power
    11
    Yip using C. Question tho, I notice the double slash. That would be ok, if the string is hard coded, but I will be having the user input the dir.

    Would that cause problems?
  6. #4
  7. *bounce*
    Devshed Novice (500 - 999 posts)

    Join Date
    Jan 2002
    Location
    Delft, The Netherlands
    Posts
    514
    Rep Power
    42
    No, no problems. The double-backslash is only necessary for string constants. They're necessary for the compiler, not for the OS :)
    "A poor programmer is he who blames his tools."
    http://analyser.oli.tudelft.nl/

IMN logo majestic logo threadwatch logo seochat tools logo