Note that there are some explanatory texts on larger screens.

plurals
  1. POSaving a C struct with a char* string into a file
    primarykey
    data
    text
    <p>I'm trying to save a struct with a char* string into a file. </p> <pre><code>struct d_object { int flags; int time; int offset; char *filename; }; </code></pre> <p>The problem is that when doing that I will obviously only save the address of that pointer rather than the string. So what I've done is simply use a character array and but I'm forced to set the maximum size of the string. This works fine, however I was wondering if there is anyway of storing the struct with a char* (that I malloc at some point) in a file and then retrieve it. I can save the string and the struct separate and then retrieve them but it's quite a mess. It would be preferable if I could load and save the entire struct (the one above) into the file. Thanks!</p> <p>The code with the char array is below:</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;string.h&gt; #include &lt;fcntl.h&gt; struct d_object { int flags; int time; int offset; char filename[255]; }; int main(int argc, char **argv) { struct d_object fcb; fcb.flags=5; fcb.time=100000; fcb.offset=220; strncpy(fcb.filename,"myfile",255); int fd=open("testfile",O_RDWR); write(fd,&amp;fcb,sizeof(fcb)); close(fd); int fd2 = open("testfile",O_RDONLY); struct d_object new_fcb; read(fd2,&amp;new_fcb,sizeof(new_fcb)); printf("read from file testfile: %s\n",new_fcb.filename); return 0; } </code></pre> <p>P.S.: I'm not using the STREAM functions simply because this is actually meant to be run on an embedded OS that doesn't have them. I've just adapted the code for *BSD/Linux so it makes more sense when asking the question.</p>
    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