← cproj

open,read,close

577f6b354fb1b990ba81984e52b102a0338054b0 · ovidiucs · Jun 30, 2019 21:43

+32 −11 · 3 files changed

  • mylib/include/myhash.h +3 −0
  • mylib/src/myhash.c +20 −11
  • mylib/test/t_hash.c +9 −0
diff --git a/mylib/include/myhash.h b/mylib/include/myhash.h
index 45a8a13..b46942f 100644
--- a/mylib/include/myhash.h
+++ b/mylib/include/myhash.h
@@ -22,3 +22,6 @@ extern HashNode *h_insert (HashTable *hTable, char *key, char *value);
 extern HashTable *h_create ( unsigned int size );
 extern HashNode *h_search (HashTable *hTable, char *key);
 extern void h_delete (HashTable *hTable, char *key);
+extern int openFile(const char *fn);
+extern int readFile(int fd);
+extern int closefile(int fd);
diff --git a/mylib/src/myhash.c b/mylib/src/myhash.c
index 8bad99e..b398bba 100644
--- a/mylib/src/myhash.c
+++ b/mylib/src/myhash.c
@@ -6,6 +6,7 @@
 #include <sys/types.h>
 #include <sys/stat.h>
 #include <fcntl.h>
+#include <unistd.h>
 
 
 #define DEFAULT_HASH_SIZE 97
@@ -181,27 +182,35 @@ void h_delete (HashTable *hTable, char *key) {
    * (HashNode **) $83 = 0x00005555555592a8
 	 */
 }
-void openFile (const char *fn) {
+int openFile (const char *fn) {
 		// Return value for open()
 		int inputFd;
-		// Output fd
-		int outputFd = 2; // stderr
 		// buffer
-
 		inputFd = open(fn,O_RDONLY);
-
+		if (inputFd == -1){
+			perror("Error on open");
+		}
+		return inputFd;
 }
 
-void readFile (int fd) {
+int readFile (int fd) {
 	// Read bytes from fd int numRead for read () 3rd arg
-	ssize_t numRead;
+	ssize_t countRead;
+
+	// Output file descriptor
+	int outputFd = 1; // stdout
+
 	// Set buffer for void *buf arg
 	char buf[BUFF];
-	while( (numRead = read (fd, buf, BUFF) > 0) {
 
-	}
+	while ((countRead = read (fd, buf, BUFF)) > 0)
+		//empty buffer
+			if (write(outputFd, buf, countRead) != countRead)
+				fprintf(stderr,"Could not write whole buffer.\n");
 }
 
-void closeFile(fd){
-
+int closeFile(fd){
+	if ( close(fd) == -1)
+			perror("Error on close\n");
+	return 0;
 }
diff --git a/mylib/test/t_hash.c b/mylib/test/t_hash.c
index d9177f6..391ea5c 100644
--- a/mylib/test/t_hash.c
+++ b/mylib/test/t_hash.c
@@ -60,6 +60,15 @@ int main(int argc, char** argv){
 	h_delete(tableResult,"400");
 	dumpTable(tableResult);
 
+	// assign the file descriptor to the integer x
+	// and attempt to open a file
+	int x = openFile("../testdata");
+	fprintf(stderr,"%d\n",x);
+	// read the file
+	int r = closefile(x);
+	fprintf(stderr,"%d\n",r);
+
+
 #if 0
 	int i = 0;