Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>If you want your changes to be reflected in the on-disk file, you must map the file as <code>MAP_SHARED</code>, not <code>MAP_PRIVATE</code>.</p> <p>Additionally, you cannot extend the file simply by writing beyond the end of the mapping. You must use <code>ftruncate()</code> to extend the file to the new size, then change the mapping to include the new portion of the file. The portable way to change the mapping is to unmap the mapping then recreate it with the new size; on Linux you can instead use <code>mremap()</code>.</p> <p>Your <code>len</code> and <code>len_file</code> variables should be of type <code>size_t</code>, and you should use <code>memcpy()</code> rather than <code>strcat()</code>, since you know exactly the length of the string, exactly where you want to copy it, and you <em>don't</em> want to copy the null-terminator.</p> <p>The following modification of your code works on Linux (using <code>mremap()</code>) :</p> <pre><code>#define _GNU_SOURCE #include&lt;stdio.h&gt; #include&lt;stdlib.h&gt; #include&lt;string.h&gt; #include&lt;unistd.h&gt; #include &lt;sys/types.h&gt; #include &lt;sys/stat.h&gt; #include&lt;sys/mman.h&gt; #include&lt;fcntl.h&gt; #define FILEMODE S_IRWXU | S_IRGRP | S_IROTH #define MAX 150 int main(int argc,char *argv[]) { int fd, ret; size_t len_file, len; struct stat st; char *addr; char buf[MAX]; if (argc &lt; 2) { printf("Usage a.out &lt;filename&gt;\n"); return EXIT_FAILURE; } if ((fd = open(argv[1],O_RDWR | O_CREAT, FILEMODE)) &lt; 0) { perror("Error in file opening"); return EXIT_FAILURE; } if ((ret = fstat(fd,&amp;st)) &lt; 0) { perror("Error in fstat"); return EXIT_FAILURE; } len_file = st.st_size; /*len_file having the total length of the file(fd).*/ if ((addr = mmap(NULL,len_file,PROT_READ|PROT_WRITE,MAP_SHARED,fd,0)) == MAP_FAILED) { perror("Error in mmap"); return EXIT_FAILURE; } while ((fgets(buf,MAX,stdin)) != NULL) { len = len_file; len_file += strlen(buf); if (ftruncate(fd, len_file) != 0) { perror("Error extending file"); return EXIT_FAILURE; } if ((addr = mremap(addr, len, len_file, MREMAP_MAYMOVE)) == MAP_FAILED) { perror("Error extending mapping"); return EXIT_FAILURE; } memcpy(addr+len, buf, len_file - len); printf( "Val:%s\n",addr ) ; //Checking purpose } if((msync(addr,len,MS_SYNC)) &lt; 0) perror("Error in msync"); if( munmap(addr,len) == -1) perror("Error in munmap"); printf("addr %p\n",addr); return 0; } </code></pre>
 

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