commit fd22de38ff77200ac4c4da8b23c6cdec1a3076ae
parent a41bc0926d3d369009bf864cffafe83313b73c30
Author: zavok <an2qzavok@gmail.com>
Date: Sun, 1 Mar 2020 22:54:39 +0300
printrow and getrow funcs
Diffstat:
M | svex.c | | | 73 | ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++------- |
1 file changed, 66 insertions(+), 7 deletions(-)
diff --git a/svex.c b/svex.c
@@ -1,3 +1,6 @@
+/* following line is required to make dprintf work */
+#define _POSIX_C_SOURCE 200809L
+
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
@@ -11,9 +14,11 @@ char *argv0;
char *fname;
char *buff;
-ulong blen;
+long blen;
void load(void);
+char* getrow(long);
+int printrow(long);
void
usage (void)
@@ -25,6 +30,8 @@ usage (void)
int
main (int argc, char *argv[])
{
+ char *ip, ibuf[1024];
+ long n;
blen = 0;
buff = 0;
ARGBEGIN{
@@ -32,8 +39,20 @@ main (int argc, char *argv[])
} ARGEND
if (argc == 0) usage();
if (argc > 1) usage();
- fname = argv[1];
+ fname = argv[0];
load();
+ for (;;){
+ n = read(0, ibuf, 1024);
+ ip = ibuf;
+ ibuf[n] = 0;
+ switch (ip[0]){
+ case 'q':
+ exit(0);
+ break;
+ default :
+ printf("?\n");
+ }
+ }
return 0;
}
@@ -41,15 +60,55 @@ void
load(void)
{
int f;
- ulong n;
- char b[1024], *bp;
- bp = buff;
+ long n;
+ char b[1024];
f = open(fname, O_RDONLY);
+ if (f == -1) {
+ dprintf(2, "failed to open file %s!\n", fname);
+ exit(-1);
+ }
while ((n = read(f, b, 1024)) > 0){
buff = realloc(buff, blen + n);
- memcpy(bp, b, n);
- bp += n;
+ memcpy(buff+blen, b, n);
blen += n;
}
close(f);
}
+
+char*
+getrow(long rn)
+{
+ char *p;
+ long n;
+ n = 0;
+ p = buff;
+ while (n < rn) {
+ if (*p == '\n') n++;
+ p++;
+ if (p > buff + blen) return 0;
+ }
+ return p;
+}
+
+int
+printrow(long rn)
+{
+ char *p;
+ p = getrow(rn);
+ printf("---[ %d ]----------\n", rn);
+ for (;;) {
+ switch (*p){
+ case '\t':
+ write(1, "\n", 1);
+ break;
+ case '\n':
+ write(1, "\n\n", 2);
+ return 0;
+ default:
+ write(1, p, 1);
+ }
+ p++;
+ if (p > buff+blen) return -1;
+ }
+ return 0;
+}