#include <fcntl.h> // O_RDONLY
#include <unistd.h>
#include <sys/stat.h> // open, stat and statbuf (get_filesize function)
#include "common.h"
/* the read function's third argument is only important for the blocksize coming to&from disk */
/* NOTHING TO DO with size to read; see r_read.c */
#define BUFFSIZE 12
int
get_filesize(char *path)
{
struct stat statbuf;
if (stat(path, &statbuf) == -1)
return (-1);
else
return (int) statbuf.st_size;
}
int main(void) {
int filesize = 0;
int counter = 0;
size_t size_to_read = 0; // NOT necessarily int but POSIX says must be unsigned int
char * filename = "readblock.c";
char * buf;
ssize_t bread = 0;
filesize = get_filesize(filename);
if (filesize == -1) {
printf("problem getting filesize, returned -1 meaning ERROR\n\n");
return -1;
}
if (BUFFSIZE < (int)filesize) {
size_to_read = BUFFSIZE;
if ((buf = (char *)malloc(size_to_read+1)) == NULL) {
printf("malloc error for %d bytes\n\n", size_to_read);
}
} else {
size_to_read = filesize;
if ((buf = (char *)malloc(size_to_read+1)) == NULL) {
printf("malloc error for %d bytes\n\n", size_to_read);
}
}
memset(buf, 'h', size_to_read+1);
buf[size_to_read]='\0';
printf("original: %s\n", buf);
printf("before reading %d: (values are one less because of array notation)\n", (int)size_to_read);
printf("at position %d the value %c \n", size_to_read-2, buf[size_to_read-2]);
printf("at position %d the value %c \n", size_to_read-1, buf[size_to_read-1]); // print last character read
printf("at position %d the value %c \n", size_to_read, buf[size_to_read]);
int fd = open(filename, O_RDONLY);
if (fd < 0) {
printf("error in %s for reading\n", filename);
return -1;
}
bread = read(fd, buf, size_to_read);
/* bread = read(fd, buf, filesize); GULPS gulps entire file; why doesn't stop at filesize?? that's why segfault */
if (bread == -1) {
printf("read error\n\n");
return -1;
}
printf("the %d first bytes of %s in hexadecimal ", size_to_read, filename);
// while (buf) { // keeps going and going ... SEGFAULTINg: question answered: does not append SHIT onto buf
// printf(" %x ", *buf);
// buf++;
// }
while (counter < size_to_read) {
counter++;
}
// okay since counter starts at 0 and bread is always > 0
printf("later: %s\n", buf);
printf("after reading %d: (values are one less because of array notation)\n", (int)size_to_read);
printf("at position %d the value %c \n", counter-1, buf[counter-1]);
printf("at position %d the value %c \n", counter, buf[counter]); // print last character read
printf("at position %d the value %c \n", counter+1, buf[counter+1]);
return 0;
}
return to top