-2

I am new to C. I have been searching for hours to find an answer to this problem but no luck. Your help would be greatly appreciated.

I need to write a function that takes the file path as argument (I am calling this argument WorkingDir below)

This function

void test1(char *WorkingDir)
{
    FILE *out_file1;
    out_file1 = fopen(strcat(WorkingDir,"Th.txt"), "wt"); 
    // the above attempts to open file   /WorkingDir/Th.txt
    fclose(out_file1);
}

called as

test1("/my/directory/")

does not work (it does not set the path as required), although this one works just fine

void test2(char *WorkingDir) #argument is not used anywhere
{
    char path[100]="/my/directory/";
    FILE *out_file1;
    out_file1 = fopen(strcat(path,"Th.txt"), "wt");
    fclose(out_file1);
}

Thank you all for your answers. An important detail that I did not mention is that I am calling the C function from R. To pass a string from R to C requires char ** argument. So this function sets the path as required:

void test101(char **WorkingDir){
    const int MAX_PATH = 300;
    char path_name[MAX_PATH + 1];
    snprintf(path_name,MAX_PATH,"%s%s",*WorkingDir,"Th.txt");
}

The above function uses your inputs. Thank you for them.

papgeo
  • 427
  • 3
  • 13

3 Answers3

3

strcat adds characters to the end of an array of characters. You can't modify a constant. So when you pass in a constant, it fails. You have to allocate a new array of chars, copy your working dir in, and then concatenate your additional path. Or use sprintf instead of strcat, but otherwise the same.

bmargulies
  • 97,814
  • 39
  • 186
  • 310
0

strcat appends to first argument, so what you are doing is neither correct nor secure. Allocate enough space to hold path name.

const int MAX_PATH = 300;
char path_name[MAX_PATH + 1];

Copy argument into path_name (use snprintf for that) and append file name (use snprintf for that as well).

void test(char *dir)
{   FILE *fp;
    size_t len_dir, len_file;

    len_dir = strlen(dir);
    len_file = strlen("Th.txt");

    assert(len_dir + len_file <= MAX_PATH);

    snprintf(path_name, MAX_PATH, "%s%s", dir, "Th.txt");

    fp = fopen(path_name, "wt");
    if(fp)
    {   // process file
        fclose(fp);
    }
}
mrk
  • 3,061
  • 1
  • 29
  • 34
  • 1
    please don't use `strncpy`, it sometimes does not generate a null-terminated string. Use `snprintf` instead. – M.M Oct 06 '14 at 00:37
-2
test1("/my/directory/")

passes a const char pointer (const char*) to a readonly (non-mutable) string. You're probably getting a SIGSEGV.

you're passing a const char*; not a char*

IRocks
  • 89
  • 1
  • 5