Note that there are some explanatory texts on larger screens.

plurals
  1. POHow can I copy the contents of argv[] into a c style string?
    primarykey
    data
    text
    <p>I'm trying to write a program that takes several arguments at runtime to append text to a file. </p> <p>The program produces a segmentation fault at runtime. Here is the code: </p> <pre><code>int main(int argc, char* argv[]) { //error checking if (argc &lt; 1 || argc &gt; 4) { cout &lt;&lt; "Usage: -c(optional - clear file contents) &lt;Filename&gt;, message to write" &lt;&lt; endl; exit(EXIT_FAILURE); } char* filename[64]; char* message[256]; //set variables to command arguments depending if -c option is specificed if (argc == 4) { strcpy(*filename, argv[2]); strcpy(*message, argv[3]); } else { strcpy(*filename, argv[1]); strcpy(*message, argv[2]); } int fd; //file descriptor fd = open(*filename, O_RDWR | O_CREAT, 00000); //open file if it doesn't exist then create one fchmod(fd, 00000); return 0; } </code></pre> <p>I am still quite a beginner and I'm having immense trouble understanding c strings. What's the difference between char* and char[] and char* []? </p> <p>UPDATE:</p> <p>The code still throws a segmentation fault, here is my revised code:</p> <pre><code>using std::cout; using std::endl; int main(int argc, char* argv[]) { //error checking if (argc &lt; 1 || argc &gt; 4) { cout &lt;&lt; "Usage: -c(optional - clear file contents) &lt;Filename&gt;, message to write" &lt;&lt; endl; exit(EXIT_FAILURE); } char filename[64]; char message[256]; //set variables to command arguments depending if -c option is specificed if (argc == 4) { strncpy(filename, argv[2], 64); strncpy(message, argv[3], 256); } else { strncpy(filename, argv[1], 64); strncpy(message, argv[2], 256); } int fd; //file descriptor fd = open(filename, O_RDWR | O_CREAT, 00000); //open file if it doesn't exist then create one fchmod(fd, 00000); return 0; } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload