How can I copy the contents of argv[] into a c style string?
char* filename[64]
creates an array of 64 pointers. You intend to create space for a string with 64 characters - this would be char filename[64]
. Because you only allocated space for pointers, and never made the pointers point to any memory, you get a seg fault.
Solution: use char filename[64];
This creates a block of 64 bytes for your string; the value filename
points to the start of this block and can be used in a copy operation
strcpy(filename, argv[2]);
I would strongly recommend using the "copy no more than n characters" function - this prevents a really long argument from causing buffer overflow. Thus
strncpy(filename, argv[2], 64);
would be safer. Even better
strncpy(filename, argv[2], 63);filename[63] = '\0';
This guarantees that the copied string is null terminated.
You have the same problem with message
. I don't think you need the code repeating...
Let me know if you need more info.
UPDATE
Today I learnt about the existence of strlcpy
- see this answer. It will take care of including the NUL
string terminator even when the original string was longer than the allocated space. See this for a more complete discussion, including the reasons why this function is not available on all compilers (which is of course a major drawback if you are trying to write portable code).
Since you have tagged this as C++ (and no one has yet mentioned it):
argv
is already a C-style array, so there is no need to copy it to another (unless you just want to waste space). If you really wanted to copy it into something, a std::string
object would be a better approach:
int main(int argc, char* argv[]){ // assuming your conditional checks are already done here ... std::string filename = argv[1]; std::string message = argv[2]; // do something return 0;}
Your variables filename
and message
are char
pointer arrays, not C-style strings (which should be null-terminated char
arrays). So you need to declare their type as:
char filename[64];char message[256];
and use strcpy
as:
strcpy(filename, argv[2]);strcpy(message, argv[3]);
the call to open
is similar:
fd = open(filename, O_RDWR | O_CREAT, 00000);