0

I have been trying to figure out how to (in C) put "getenv()" and "/filetest" into one char.

I've thought that you could do it by putting:

char *file = getenv("HOME") + "/filetest";

But, I can't seem to figure it out.

I tried after that to do:

char *file = getenv("HOME") && "/filetest";

But that didn't work either..

Then, I tried:

char *file1 = getenv("HOME");
char *file = file1 + "/filetest";

Could someone please tell me what I am doing wrong?

0NeXt
  • 1
  • 2

2 Answers2

1

Allocate a buffer big enough to hold the two strings, and then use strcat() to concatenate string2 to string1:

char buffer[BUFSIZ];

strcat (strcpy (buffer, getenv ("HOME"), "/filetest");

/* OR, more readable to modern eyes: */
strcpy (buffer, getenv ("HOME");
strcat (buffer, "/filetest");

/* OR */
unsigned offset = 0;

strcpy (buffer + offset, tmp);
offset += strlen (tmp);
strcpy (buffer + offset, "/filetest");

/* OR */
strcpy (buffer, tmp);
strcpy (buffer + strlen (tmp), "/filetest");

/* OR */
int n = snprintf (buffer, sizeof buffer, "%s", tmp);
snprintf (buffer + n, sizeof buffer - (size_t) n, "%s", "/filetest");

Note that getenv() indicates failure by returning a NULL pointer constant, code should check its result before the call to strcpy().

char *tmp = getenv ("HOME");

if (!tmp) {
    complain ();
}
/* Now copy. */
Harith
  • 4,663
  • 1
  • 5
  • 20
0

In C, string copy / concatenation is performed by strcpy / strcat:

https://www.tutorialspoint.com/c_standard_library/c_function_strcpy.htm https://www.tutorialspoint.com/c_standard_library/c_function_strcat.htm

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

int main() {
    char file[200];
    strcpy(file, getenv("HOME"));
    strcat(file, "/filetest");
    
    printf("%s", file);
    printf("\n\n");
    return 0;
}
ckc
  • 345
  • 4
  • 12