Thread: Implementation of linux cp (copy) command in C language

Hybrid View

Previous Post Previous Post   Next Post Next Post
  1. #1
    Registered User
    Join Date
    Sep 2011
    Posts
    11
    How do I obtain the full path of the current directory I am in. Is there any system call for that? Trying to play with above program a little.

  2. #2
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    You do this a lot without allocating more space, which is very bad:

    Code:
          strcat(dest, "/");
          strcat(dest, src);
    Here dest is a pointer to one of main()'s argv parameters; you do something similiar with the same pointer again when it is copied into some of your functions. Would you consider this acceptable:

    Code:
    char eg[]="hello world,";
    strcat(eg, " okay, no space allocated for this!");
    If so, you do not understand arrays in C properly -- you should figure out or ask why this is wrong before you do ANYTHING else. If you do not fix this, eventually your program will start seg faulting (I'm surprised it doesn't now; very likely it will if you compile it on a machine with a slightly different compiler or architecture).

    If you do understand but had forgotten the issue of proper memory management because you are new to C, I'd suggest you use something like this:

    Code:
    #include <limits.h>
    
    [....]
    char dest[PATH_MAX+1];
    strcpy(dest, av[2]);
    PATH_MAX is a system constant found in limits.h on *nix systems. It represents the maximum length, in bytes, for an absolute file path. Ie, no filename including the path can possibly be longer than that (usually it is 4096). So if you are just building paths in there, it will be long enough to hold all your strcat's, etc.
    Last edited by MK27; 11-17-2011 at 10:44 AM.
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Creation of a Command Language Interpreter
    By Sicilian_10 in forum C Programming
    Replies: 18
    Last Post: 04-16-2010, 06:36 AM
  2. Simple copy command
    By Danieljax88 in forum C Programming
    Replies: 5
    Last Post: 04-01-2010, 04:04 PM
  3. How to hide command prompt using C language?
    By deob in forum C Programming
    Replies: 6
    Last Post: 03-24-2009, 08:17 PM
  4. copy command
    By munna_dude in forum C Programming
    Replies: 16
    Last Post: 06-20-2007, 11:12 PM
  5. C implementation of unix ls command
    By sinkovich in forum Linux Programming
    Replies: 0
    Last Post: 02-24-2003, 04:38 AM