ProgrammingThis forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.
Notices
Welcome to LinuxQuestions.org, a friendly and active Linux Community.
You are currently viewing LQ as a guest. By joining our community you will have the ability to post topics, receive our newsletter, use the advanced search, subscribe to threads and access many other special features. Registration is quick, simple and absolutely free. Join our community today!
Note that registered members see fewer ads, and ContentLink is completely disabled once you log in.
If you have any problems with the registration process or your account login, please contact us. If you need to reset your password, click here.
Having a problem logging in? Please visit this page to clear all LQ-related cookies.
Get a virtual cloud desktop with the Linux distro that you want in less than five minutes with Shells! With over 10 pre-installed distros to choose from, the worry-free installation life is here! Whether you are a digital nomad or just looking for flexibility, Shells can put your Linux machine on the device that you want to use.
Exclusive for LQ members, get up to 45% off per month. Click here for more info.
char *string1 = "Here is a sample file.";
char *string2 = "a";
char *sub;
sub = strstr( string1, string2 );
if (sub) {
printf( "%s\n", strndup( string1, sub - string1 ) ); // !!!
}
Note that strndup() allocates memory for you, so you would be better to save the return pointer and free() it later. If your program is short and doesn't use much memory you can get by without it, but I think you would run into problems if you tried to scale up (memory leaks), so it's better to do it correctly from the start...
Also, does anybody know if strcpy() would copy over a char * c? or do both arguments have to be char c[100]? And if that is the case how can I get around this? I dont want to have a fixed size. thanks.
Yes, but the buffer pointed to by c has to be large enough to contain the data - if you have a 50 character string and you try to strcpy it into a 40 character buffer, you're either going to cause a crash or start writing over memory that you shouldn't, with god-knows-what consequences. Also, unless you check the sizes of your buffers beforehand, you really shouldn't use strcpy over strncpy.
LinuxQuestions.org is looking for people interested in writing
Editorials, Articles, Reviews, and more. If you'd like to contribute
content, let us know.