writefile.c (1893B)
1 #include <u.h> 2 #include <libc.h> 3 #include <venti.h> 4 #include <libsec.h> 5 #include <thread.h> 6 7 enum 8 { 9 Blocksize = 8192 10 }; 11 12 int chatty; 13 14 void 15 usage(void) 16 { 17 fprint(2, "usage: writefile [-v] [-h host] < data\n"); 18 threadexitsall("usage"); 19 } 20 21 void 22 threadmain(int argc, char *argv[]) 23 { 24 int n; 25 uchar score[VtScoreSize]; 26 uchar *buf; 27 char *host; 28 vlong off; 29 VtEntry e; 30 VtRoot root; 31 VtCache *c; 32 VtConn *z; 33 VtFile *f; 34 35 quotefmtinstall(); 36 fmtinstall('F', vtfcallfmt); 37 fmtinstall('V', vtscorefmt); 38 39 host = nil; 40 ARGBEGIN{ 41 case 'V': 42 chattyventi++; 43 break; 44 case 'h': 45 host = EARGF(usage()); 46 break; 47 case 'v': 48 chatty++; 49 break; 50 default: 51 usage(); 52 break; 53 }ARGEND 54 55 if(argc != 0) 56 usage(); 57 58 buf = vtmallocz(Blocksize); 59 60 z = vtdial(host); 61 if(z == nil) 62 sysfatal("could not connect to server: %r"); 63 64 if(vtconnect(z) < 0) 65 sysfatal("vtconnect: %r"); 66 67 // write file 68 c = vtcachealloc(z, Blocksize*32); 69 if(c == nil) 70 sysfatal("vtcachealloc: %r"); 71 f = vtfilecreateroot(c, Blocksize, Blocksize, VtDataType); 72 if(f == nil) 73 sysfatal("vtfilecreateroot: %r"); 74 off = 0; 75 vtfilelock(f, VtOWRITE); 76 while((n = read(0, buf, Blocksize)) > 0){ 77 if(vtfilewrite(f, buf, n, off) != n) 78 sysfatal("vtfilewrite: %r"); 79 off += n; 80 if(vtfileflushbefore(f, off) < 0) 81 sysfatal("vtfileflushbefore: %r"); 82 } 83 if(vtfileflush(f) < 0) 84 sysfatal("vtfileflush: %r"); 85 if(vtfilegetentry(f, &e) < 0) 86 sysfatal("vtfilegetentry: %r"); 87 vtfileunlock(f); 88 89 // write directory entry 90 memset(&root, 0, sizeof root); 91 vtentrypack(&e, buf, 0); 92 if(vtwrite(z, root.score, VtDirType, buf, VtEntrySize) < 0) 93 sysfatal("vtwrite dir: %r"); 94 95 // write root 96 strcpy(root.name, "data"); 97 strcpy(root.type, "file"); 98 root.blocksize = Blocksize; 99 vtrootpack(&root, buf); 100 if(vtwrite(z, score, VtRootType, buf, VtRootSize) < 0) 101 sysfatal("vtwrite root: %r"); 102 103 print("file:%V\n", score); 104 threadexitsall(0); 105 }