Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple C string manipulation

Tags:

c

string

I trying to do some very basic string processing in C (e.g. given a filename, chop off the file extension, manipulate filename and then add back on the extension)- I'm rather rusty on C and am getting segmentation faults.

char* fname;
char* fname_base;
char* outdir;
char* new_fname;
.....
fname = argv[1];
outdir = argv[2];
fname_len = strlen(fname);
strncpy(fname_base, fname, (fname_len-4)); // weird characters at the end of the truncation?
strcpy(new_fname, outdir); // getting a segmentation on this I think

strcat(new_fname, "/");
strcat(new_fname, fname_base);
strcat(new_fname, "_test");
strcat(new_fname, ".jpg");
printf("string=%s",new_fname);  

Any suggestions or pointers welcome.

Many thanks and apologies for such a basic question

like image 204
trican Avatar asked Apr 10 '26 06:04

trican


2 Answers

You need to allocate memory for new_fname and fname_base. Here's is how you would do it for new_fname:

new_fname = (char*)malloc((strlen(outdir)+1)*sizeof(char));

In strlen(outdir)+1, the +1 part is for allocating memory for the NULL CHARACTER '\0' terminator.

like image 152
Pablo Santa Cruz Avatar answered Apr 11 '26 20:04

Pablo Santa Cruz


In addition to what other's are indicating, I would be careful with

strncpy(fname_base, fname, (fname_len-4));

You are assuming you want to chop off the last 4 characters (.???). If there is no file extension or it is not 3 characters, this will not do what you want. The following should give you an idea of what might be needed (I assume that the last '.' indicates the file extension). Note that my 'C' is very rusty (warning!)

char *s;
s = (char *) strrchr (fname, '.');
if (s == 0)
{
    strcpy (fname_base, fname);
}
else
{
    strncpy (fname_base, fname, strlen(fname)-strlen(s));
    fname_base[strlen(fname)-strlen(s)] = 0;
}
like image 30
Edward Leno Avatar answered Apr 11 '26 20:04

Edward Leno



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!