hello. i'm new here and new to C programming so would appreciate any help with a problem i have. how can i copy the contents of a command line argument e.g. argv[1] to a string declared within main() e.g. filename[30]

cheers.....
PS this isn'y my homework:lol:

Recommended Answers

All 19 Replies

Try memcpy or strcpy.

2.14.4 memcpy

Declaration:

void *memcpy(void *str1, const void *str2, size_t n);

Copies n characters from str2 to str1. If str1 and str2 overlap the behavior is undefined.

Returns the argument str1.

2.14.13 strcpy

Declaration:

char *strcpy(char *str1, const char *str2);

Copies the string pointed to by str2 to str1. Copies up to and including the null character of str2. If str1 and str2 overlap the behavior is undefined.

Returns the argument str1.

i've tried strcpy() but when i compile and run it the prog hangs then crashes. i'm probably doing something basically wrong in the fubction maybe.

int main(int argc, char *argv[]){
    
    char filename[30];
    strcpy(filename, argv[1]);
    
}

i've tried strcpy() but when i compile and run it the prog hangs then crashes. i'm probably doing something basically wrong in the fubction maybe.

int main(int argc, char *argv[]){
    
    char filename[30];
    strcpy(filename, argv[1]);
    
}

Yes probably U R doing something wrong. What R U passing as arg[1]? Probably nothing and thats why it crashes.

#include <stdio.h>
#include <string.h>

int main(int argc, char *argv[]){
    
   char filename[30];
   if (argc != 2)
   {
      printf("Dude are you passing something at all");
      return 1;   
   }
   strcpy(filename, argv[1]);
   printf("filename: %s\n", filename);
   return 0;
}

This works for me.
PS: memcpy is safer

D'oh! just going to crawl into a hole and die to save the embarassment!!:eek:
cheers for your help....

Its not a big deal, everyone mistakes and we learn from it.

I also want to read filename, but in addition I need to read some interger parameter. I used this, now want to change. How can I handle: ./progname infilename integer ?

int main(){    
         ifstream input;                                  
		 input.open("filename");                           
		 if (!input)
		 {
                cout<<"File not open";
                exit(1);
                }
     getline(input, str);
     return 0;
}

> PS: memcpy is safer
No it's not. It will try to copy n characters whether it hits an architecture-dependent read boundary or not. Use strncpy(). It is fully standard and stops in the right place.

To convert a string to an integer #include <cstdlib> and use the atoi() function: int i = atoi( "42" ); Also, this is the C forum. If you plan to use C++ please post in the C++ forum. While the same people frequent both, the advice you get will vary depending on the language. (C and C++ are significantly different languages.)

Hope this helps.

>i'm probably doing something basically wrong in the fubction maybe.
Are you passing any arguments to your program? If not, argv[1] isn't guaranteed to be there, and if it is, it's pretty much sure to be NULL. If you're passing something, make sure that it's less than 30 characters or you'll overflow the buffer. strncpy is the logical choice, but it's really poorly named and doesn't do quite what you're expecting. I'd say use strncat instead:

#include <string.h>

int main ( int argc, char *argv[] )
{
  char buffer[30];

  if ( argc > 1 ) {
    /* strncat won't work if buffer isn't already a string */
    buffer[0] = '\0';
    strncat ( buffer, argv[1], 29 );
  }

  return 0;
}

>It will try to copy n characters whether it hits an
>architecture-dependent read boundary or not.
An architecture-dependent read boundary? Can you describe what you mean by this?

>Use strncpy(). It is fully standard and stops in the right place.
memcpy is fully standard. Also, strncpy always copies n characters. If the string isn't shorter than the buffer, strncpy will pad the buffer all the way to the count with null characters. If the string is longer than the buffer, strncpy will fail to null terminate the buffer. Despite the name, strncpy shouldn't be used as a "count restricted strcpy".

>To convert a string to an integer #include <cstdlib> and use the atoi() function
I wouldn't recommend atoi unless you've completely validated the input string first. It's basically impossible to tell if atoi failed without prior validation, and if the string isn't representable as an integer then calling atoi produces undefined behavior. It's too risky, so you should use strtol instead:

char *end;
long temp;
int x;

errno = 0;
temp = strtol ( buffer, &end, 0 );

if ( end == buffer )
  puts ( "No conversion made" );
else if ( *end != '\0' )
  puts ( "Partially invalid string" );
else if ( temp < INT_MIN || temp > INT_MAX )
  puts ( "Out of range value" );
else
  x = (int)temp;

I never said memcpy() wasn't standard. Only that strncpy() was also.
The difference in choice is this: do you own/did you allocate the memory you are accessing? If not, you may very well be playing with fire to try reading (or writing) past the end of memory you have not allocated.

The strncpy() function always pads the target out to n bytes. However, it stops reading the source when it hits the end of the string, which the C specification guarantees to be there in argv[].

You are correct about watching the end of string, as strncpy() does not guarantee that the target is null-terminated.

I will agree that the use of strncat() is the best choice so far, since it addresses both issues nicely.

The strtol() has the same validation problems as stroi(). Just because it returns something different... But you are right in that it is a little more convenient for catching incomplete conversions...

Cheers.

Member Avatar for iamthwee

I think stroi is a typo.

Heh, yes, so it is. I meant atoi().

Member Avatar for iamthwee

[off topic]
Do you have a link detailing how you uv unwrapped that rigged blender model? :)
It is always something I've been meaning to do but never got round to it. Or did you use a python script?

Are you talking about that Billy model in "Action Constraints Made Easy" or Waffler's pink girl?
I don't think I did anything particularly amazing in either one... (or maybe you are thinking of someone else?)

Hmm... I did spend some time on Billy's shoes...
There is a tutorial (in the tutorials section) that helped me a lot about properly unwrapping a face and head. The real trick is to select only the faces that define the shape first, LSCM, adjust, pin, select more faces, repeat...

/me goes to figure out what I did

Member Avatar for iamthwee

Ah you rigged waffler's pink girl too?

Yeah I was talking bout the billy model. But yeah what's good video tutorials?

Alas, I've never had much patience for video tutorials. The ones at ibiblio are usually okay but I haven't spent much time looking through them.

If you really thing a tut is a good idea I can cobble one together sometime within the next week or so, or at least link to some good ones I can find that do what I did.

I don't know if you remember or not, but Waffler did his "Pink Girl" 2D sketch and I thought it would be fun to model and rig. So we both (and I think one other) did a bunch of pink girls. I tried to get everything to look as cartooney as the original, but cipix and a few others modified my facial textures to be more pen-and-ink-ish. But I think my pink girl was the only one that was ever fully rigged. She's only slightly more complex than Billy though... The arms and legs are wobbly tubes (rigged with IK chains) in both.

Both the files can be downloaded and you can look at the UV mapping in them.

>I never said memcpy() wasn't standard.
The implication was there. Just think of it as adding to your answer rather than correcting you.

>If not, you may very well be playing with fire to try reading
>(or writing) past the end of memory you have not allocated.
I don't even know what you're trying to say anymore. Perhaps if you gave some examples that show your point more clearly. It seems like you're trying to make strncpy somehow better than memcpy because the count represents an "at most" count rather than a hard count.

In that case, owning the source is irrelevant provided you use a sane value for the count argument. For example, the count would be acquired by calling strlen on the source and then verifying that the destination is big enough to handle it. Whether you're using memcpy or strncpy (or strcpy for that matter), it's wise to get your destination size right, which typically means learning the size of the source.

>However, it stops reading the source when it hits the end of the string
Yes, that's typical of the str* functions, whereas the mem* functions take a count rather than assuming a null terminated string for the source.

>The strtol() has the same validation problems as stroi().
No, it doesn't. It has completely defined and predictable behavior if there's a conversion error, the location and type of which you can pinpoint and recover from with ease. atoi isn't even close to strtol in robustness.

>Just because it returns something different...
And sets errno, and sets a pointer to where the conversion failed, and the return value tells you what kind of overflow (if any) occurred without invoking undefined behavior. The error detection potential of strtol is quite good.

> The implication was there.
No, it wasn't. However, I can see how it could have been read as such. I will try to be more explicit in the future.

> Perhaps if you gave some examples that show your point more clearly.
The argv array is prepared by the startup code. You did not allocate it. Therefore, you cannot make assumptions on what data you are allowed to read near it. [memory you are allowed to read][memory you are not allowed to read] The quick brown fox...\0........READ.AND.CRASH...................... When you say memcpy( mybuf, argv[ n ], 50 ); you run the very real possibility that you will will try to read something that the processor will disallow, causing your program to fail. Granted, I don't know any PC where that will happen, but the point is that you are assuming something about implementation dependent architecture.

You should instead stick to reading only that which you are given: strncat( mybuf, argv[ n ], 50 ); This (or my previously proffered strncpy()) guarantees that you are not going to violate any memory restrictions, wrap segments, or do anything else that your particular processor may spring on you, because you know that you are not reading memory that does not belong to you. Just because you've been able to get away with it on a PC for years doesn't mean that you will be able to get away with it on some other computer, or even some future PC.

I agree completely with having a sane count. The prerequisite is of course knowing the size of your source (as you have already pointed out).

As for strtol(), I've already conceded that it is superior to atoi() because "...you can pinpoint and recover from with ease" any conversion errors. However, I will now concede that it is in every way a superior choice than atoi(). (My concern was only in what you must code to recover from the error "properly" --which depends on your program goals. If you use atoi() you must find the information that strtol() gives you for free. Actual interpretation of that data is otherwise much the same.)


Alas, for new programmers I usually try not to get too deep into this junk. Only to point out when something may not be safe. Using memcpy() to read past the end of he source buffer is always unsafe. So either have a sane count (obtained by first checking the length of the source buffer) or when using strings use something that will properly terminate for you when the null is encountered, such as strncpy() or strncat().
That's all.

>you are assuming something about implementation dependent architecture
No, you're assuming that 50 is meaningful in telling you the length of the source string. The two examples are not equivalent because you're just using an arbitrary number all willy-nilly with memcpy, but taking advantage of the fact that strncat will stop at a null character while memcpy uses the count unconditionally. The equivalent memcpy to

strncat ( mybuf, argv[n], 50 );

is

size_t len = strlen ( argv[n] );

if ( len > 50 )
  len = 50;

memcpy ( mybuf, argv[n], len );
mybuf[len] = '\0';

It looks like your point is resting completely on memcpy being called incorrectly and strncat (or strncpy) being called correctly. Of course, using memcpy with strings when one of the str* functions is better suited strikes me as a poor design decision to begin with. Since it's clearly harder to get memcpy right in this case, I agree with you in principle, just not in the details. :)

Yes, yes, exactly. Thank you.

I've nothing against memcpy(). Just using it improperly.

commented: I can't believe you don't use video tutorials they save hours! Thanx +13
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.