boot2

Playing with the boostrap
git clone https://git.ryansepassi.com/git/boot2.git
Log | Files | Refs | README

010-file-roundtrip.c (1527B)


      1 /* fopen("w") + fputs + fclose, then fopen("r") + fread + fclose.
      2  *
      3  * Smoke-tests the full file I/O stack on top of P1pp sys_open /
      4  * sys_close / sys_write / sys_read:
      5  *   - fopen        -> stdio/fopen.c -> _open3 -> sys_open
      6  *   - fputs        -> stdio/fputs.c -> fputc -> _write -> sys_write
      7  *   - fclose       -> stdio/fclose.c -> close -> sys_close
      8  *   - fread        -> stdio/fread.c -> read -> _read -> sys_read
      9  *
     10  * Mes's fopen returns the fd cast to FILE*, so a single declaration of
     11  * FILE as `long` is enough to thread it through. Diagnostics use the
     12  * already-proven write() path so a failure inside fopen / fread is
     13  * easy to spot from stdout. */
     14 typedef long FILE;
     15 typedef long ssize_t;
     16 typedef unsigned long size_t;
     17 
     18 extern FILE   *fopen  (char const *path, char const *mode);
     19 extern int     fclose (FILE *stream);
     20 extern int     fputs  (char const *s, FILE *stream);
     21 extern size_t  fread  (void *ptr, size_t size, size_t count, FILE *stream);
     22 extern ssize_t write  (int fd, void const *buf, size_t n);
     23 
     24 int
     25 main (void)
     26 {
     27   char const *path = "/tmp/boot2-cclibc-10";
     28 
     29   FILE *w = fopen (path, "w");
     30   if (!w)
     31     {
     32       write (1, "fopen-w-fail\n", 13);
     33       return 1;
     34     }
     35   fputs ("hello\n", w);
     36   fclose (w);
     37 
     38   FILE *r = fopen (path, "r");
     39   if (!r)
     40     {
     41       write (1, "fopen-r-fail\n", 13);
     42       return 2;
     43     }
     44   char buf[8];
     45   size_t n = fread (buf, 1, 6, r);
     46   fclose (r);
     47 
     48   if (n != 6)
     49     {
     50       write (1, "short-read\n", 11);
     51       return 3;
     52     }
     53   write (1, buf, 6);
     54   return 0;
     55 }