0

I am trying to open a txt file for a program entering the name of the file as a command line argument. if I provide the path as a string it works, so the problem in my code is with the command line argument. I have the following:

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

int main (int argc, char* argv[])
{
    char* filename = "/path/";
    char* name = argv[1];
    printf("%s\n", filename);
    printf("%s\n", name);
    strcat(filename, name);
    printf("%s\n", filename);
    strcat(filename, ".txt");
    printf("%s\n", filename);
    return 0;
}

I run it like so:

./program filenamewithoutextension

I get the following output when I run it:

/path/
filenamewithoutextension
Segmentation fault (core dumped)

I don't understand what is happening.

NAND
  • 663
  • 8
  • 22
fati
  • 29
  • 4
  • 1
    `char* filename = "/path/";` This initializes the pointer to point to a constant read-only string. `strcat(filename, name);` This attempts to append another string past the end of the former. That causes UB (undefined behavior) right there. – dxiv May 30 '20 at 19:05
  • You need to be careful about space allocation with character arrays. You declare filename as a char array with a space of 7 (/path/ + NULL terminator). When you attempt to strcat with the name onto filename, you are writing beyond the allocated length of filename, which should be read only. – bogertron May 30 '20 at 19:06

2 Answers2

1

Note that in your code snippet filename and name are just pointers which point to read-only data, so you cannot modify the data they point to.

You can dynamically allocate memory using malloc in order to be able to edit the data they point to. Or just allocate memory for them in stack like, filename[100] or name[100].

Your code should be like that:

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

int main (int argc, char* argv[])
{
    char filename[100]; 
    char name[100];
    strcpy(filename, "/path/");
    strcpy(name, argv[1]);
    printf("%s\n", filename);
    printf("%s\n", name);
    strcat(filename, name);//You can safely modify name now 
    printf("%s\n", filename);
    strcat(filename, ".txt");//You can safely modify filename now 
    printf("%s\n", filename);
    return 0;
}
NAND
  • 663
  • 8
  • 22
0

char* filename = "/path/"; is still accepted in C to consider old code written in the early days, when the const keyword did not exist yet.
But it should be const char * because "/path/" here is actually a constant string.
(the -Wwrite-strings compiler option can help detect this)

If you want to append something to this string you need more storage for the following chars.
char filename[100]="/path/";
In this case, the 100 chars are local to your function and can be changed.
They start with the given chars but are followed by many zeroes (up to 100).

Then, afterwards, it makes sense to put some new chars after the last /.

prog-fh
  • 13,492
  • 1
  • 15
  • 30