directory help

This is a discussion on directory help within the C Programming forums, part of the General Programming Boards category; I need help im trying to make a little program that just changes the current directory but i get a ...

  1. #1
    Registered User
    Join Date
    Jul 2008
    Location
    Fort Worth TX
    Posts
    15

    directory help

    I need help im trying to make a little program that just changes the current directory but i get a segmentation fault.

    Code:
    #include <stdio.h>
    #include <unistd.h>
    
    
    int main() {
    
    
    
        char *path;
    
        printf("Which directory do you want to go to?:");
        scanf("&#37;s",&path);
        chdir(path);
        printf("yay it worked!\n");
        return 0;
    
    }

  2. #2
    Deathray Engineer MacGyver's Avatar
    Join Date
    Mar 2007
    Posts
    3,211
    Yes, a pointer just points to data. You have to make it point somewhere. Your variable path points to somewhere arbitrary. What you're doing with your scanf() call is trashing whatever memory it points to, and the OS is stopping you.

    Do something simple. Make a char array of a certain size and use fgets() to safely read in the directory (and remember to trim off the newline). There are examples on using fgets() throughout the forums and I believe possibly in the FAQ on this site.

  3. #3
    Registered User valaris's Avatar
    Join Date
    Jun 2008
    Location
    RING 0
    Posts
    507
    Code:
    #include <stdio.h>
    #include<stdlib.h>
    #include <unistd.h>
    
    
    int main() {
    
    
    
        char *path = (char *)malloc(40 * sizeof(char));
    
        printf("Which directory do you want to go to?:");
        scanf("&#37;s",path);
        chdir(path);
        printf("yay it worked!\n");
        return 0;
    }
    That should work now using your code assuming the directory isn't over 39 characters I believe.

  4. #4
    Registered User
    Join Date
    Jul 2008
    Location
    Fort Worth TX
    Posts
    15
    It works now thanks guys.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Profiler Valgrind
    By afflictedd2 in forum C++ Programming
    Replies: 4
    Last Post: 07-18-2008, 10:38 AM
  2. Couple errors please help :-D
    By JJJIrish05 in forum C Programming
    Replies: 9
    Last Post: 03-06-2008, 02:54 AM
  3. Replies: 6
    Last Post: 07-30-2003, 04:08 AM
  4. Directory reading trouble
    By samGwilliam in forum Linux Programming
    Replies: 0
    Last Post: 03-10-2002, 09:43 AM
  5. The Site Directory
    By kermi3 in forum A Brief History of Cprogramming.com
    Replies: 6
    Last Post: 01-22-2002, 08:19 PM

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