Building a path from strings in C

-1

I'm very new to C and am working on a utility that scans folders for duplicate files and then does some stuff to them. When I have the list of duplicate file names, I need to build a string with the full path and file name to manipulate the files, but I get an error every time I try to append a \ to the path, but the error does not occur if I skip the . Here is a simplified version of the problem code:

char *TARGET1 = ".";
char *TARGET2 = ".\\test"; 
char *PATH_SEP = '\\';

char *folder1_files[filecount1];  // These arrays are populated with file
char *folder2_files[filecount2];  // names elswhere in the code
int l = 0;  // The counter for the loop that is comparing the filenames

char buffer[1024];
strcpy(buffer, TARGET2);
printf("Building the path now...\n");
//strcat(buffer, PATH_SEP);
strcat(buffer, folder2_files[l]);
printf("Path: %s\n", buffer);

If I leave the third line from the bottom commented out, the program completes and I get the following output:

Path built! Path: .\testfile3.txt

If I uncomment it, I get this error: Access violation reading location 0x0000005C

Can anyone point out where this is going wrong? Is there a more standard way of building paths in C?

c
special-characters
filepath
strcat
asked on Stack Overflow Nov 6, 2017 by Troy D • edited Nov 6, 2017 by Troy D

2 Answers

1

The third line from the bottom is

int l = 0;

If you comment it out, your code will not compile, because you need to declare l before using it.

The fourth line from the bottom is

//strcat(buffer, PATH_SEP);

The line

char *PATH_SEP = '\\';

makes no sense, because you initialize string (char*) with character (char). Anything in double quotes is a string, anything in single quotes is a character. So your PATH_SEP points to a garbage.

answered on Stack Overflow Nov 6, 2017 by user31264 • edited Nov 6, 2017 by eyllanesc
1

Character constants such as PATH_SEP are not automatically NUL-terminated. When you call

strcat(buffer, PATH_SEP);

the strcat routine expects both arguments to point to NUL-terminated strings. Because PATH_SEP isn't NUL terminated the routine continues scanning memory, looking for a NUL byte. Eventually it either overwrites something important or access memory it shouldn't.

Change

char *PATH_SEP = '\\';

to

char *PATH_SEP = "\\";

and your code should perform as expected.

Best of luck.

answered on Stack Overflow Nov 6, 2017 by Bob Jarvis - Reinstate Monica • edited Nov 6, 2017 by BLUEPIXY

User contributions licensed under CC BY-SA 3.0