System Calls using C w/BASH

Hello all,

I'm attempting to write a basic application that appends an arbitrary list of txt files to one txt file.

So, for example, if the application is run like so:

appendFileToFile file1.txt file2.txt file3.txt the system command should, hopefully be, cat [theFiles] >> testfile.txt

I'm using C, then making a call to the system in BASH. However, I keep getting segmentation faults.

My code below:

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

int main(int argc, char *argv[])
{
    
    int i;
    char theCommand[] = "cat ";
  
    for (i = 1; i < argc; i++)
    {
        strcat(theCommand, argv);
    }
    strcat(theCommand, " >> testfile.txt");
    system(theCommand);

    return 0;
}

Thanks for you time.

Your buffer only has five bytes of space.

Writing beyond that is rampaging through stack space, overwriting every local variable behind it until it finds and corrupts your stack frame itself, crashing your program the next time it tries to do anything to the stack.

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

int main(int argc, char *argv[])
{
    
    int i;
    char theCommand[16384] = "cat ";
  
    for (i = 1; i < argc; i++)
    {
        strcat(theCommand, argv);
    }
    strcat(theCommand, " >> testfile.txt");
    system(theCommand);

    return 0;
}
1 Like

D'oh! That would explain the segmentation fault, then.

Thank you very much for your help!

I had to put some white space in between the files because it was concatenating them together like: file.txtfile2.txtfile3.txt, is this the acceptable way of doing it (below)?

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

int main(int argc, char *argv[])
{
    
    int i;
    char theCommand[16384] = "cat ";
  
    for (i = 1; i < argc; i++)
    {
        strcat(theCommand, argv);
        strcat(theCommand, " ");
    }
    strcat(theCommand, " >> testfile.txt");
    system(theCommand);

    return 0;
 }

It should work fine.

Try putting it before the command instead of after, though. Then you can just make your command "cat" instead of "cat ".

I would suggest you prefer strncat to strcat. strncat is the secure sister of strcat:

strncat - C++ Reference

usage of strncat is the same as strcat. The only difference is that strncat has an aditional third argument, that you use to tell the function the maximum amount of characters that should be copied to the destination buffer. This is very important to prevent your programs being vulnerable to buffer overflow errors.

for (i = 1; i < argc; i++)
    {
        strncat(theCommand, argv, sizeof(theCommand) - 1);
    }

2 Likes