title: How do I read/write a block device?
body: <p>How do I read/write a block device? I heard I read/write like a normal file so I setup a loop device by doing</p>
  
  <pre><code>sudo losetup /dev/loop4 ~/file
  </code></pre>
  
  <p>Then I ran the app on the file then the loop device</p>
  
  <pre><code>sudo ./a.out file
  sudo ./a.out /dev/loop4
  </code></pre>
  
  <p>The file executed perfectly. The loop device reads 0 bytes. In both cases I got FP==3 and off==0. The file correctly gets the string length and prints the string while the loop gets me 0 and prints nothing</p>
  
  <p>How do I read/write to a block device?</p>
  
  <pre><code>#include &lt;fcntl.h&gt;
  #include &lt;cstdio&gt;
  #include &lt;unistd.h&gt;
  
  int main(int argc, char *argv[]) {
      char str[1000];
  
      if(argc&lt;2){
          printf("Error args\n");
          return 0;
      }
  
      int fp = open(argv[1], O_RDONLY);
      printf("FP=%d\n", fp);
      if(fp&lt;=0) {
          perror("Error opening file");
          return(-1);
      }
      off_t off = lseek(fp, 0, SEEK_SET);
      ssize_t len = read(fp, str, sizeof str);
      str[len]=0;
      printf("%d, %d=%s\n", len, static_cast&lt;int&gt;(off), str);
  
      close(fp);
  }
  </code></pre>