C: write (and then read) a string to file using a hash function to locate the byte's position -
i want write 1kb file, , want use hash function calculate position of byte i'm going write. want able later retrieve data in correct order.
to locate position of byte read/write use hash function
f = (index*prime) mod 1024
where index index in string, , prime prime number need avoid collisions, i.e. not rewriting 2 times in same position. f, strlen (b first create file
dd bs=1024 count=1 if=/dev/zero of=test.fs
and after compile , run program passing "w" parameter
$ ./a.out w
now, seems me write() function job correctly, because if do...
$ cat test.fs or $ hexdump test.fs
... can see content of file consistent string inserted!
however, if run read-mode passing "r" parameter, curious random output, seems me if i'm reading thrash memory. cannot understand read() function fails, thank in advance.
the c code follows:
#include <stdio.h> #include <string.h> #define prime 7919 int main(int argc, char *argv[]) { int mode; if (argc < 2) return 1; else if (strcmp (argv[1], "r") == 0) mode = 1; else if (strcmp (argv[1], "w") == 0) mode = 2; else return 1; file *fs; char buf[1024]; int val; int i; char c; if (mode == 1) { fs = fopen("test.fs", "rb"); val = read (buf, 1024, fs); if (val != 1024) fprintf(stderr, "either error occurred, or eof reached.\n"); printf("content read: %s\n", buf); } else if (mode == 2) { fs = fopen("test.fs", "wb"); printf ("enter string want write disk: "); while ((c = getchar()) != eof) buf[i++] = c; buf[i] = eof; val = write (fs, buf, strlen (buf)); if (val == eof) fprintf(stderr, "an error occurred while writing.\n"); printf("%d bytes written disk.\n"); } fclose (fs); } int write(file *f, char *str, long len) { int i; int err; (i=0; < len && err != eof; i++) { fseek(f, (i*prime)%1024, seek_set); err = fputc(str[i], f); } if (err != eof) return i; else return eof; } int read(char *buffer, long len, file *f) { int i; int br = 1; (i=0; < len && br != 0; i++) { fseek(f, (i*prime)%1024, seek_set); br = fread (&buffer[i],1,1,f); } if (ferror (f)) return eof; else return i; }
buffer
not string, array of characters. when incorrectly print string:
printf("content read: %s\n", buf);
you buffer overflow since array isn't null terminated.
Comments
Post a Comment