I am playing around with the read(), write(), and open() system calls. I wrote a function to open/create 3 files, a function to write a test message to the files, and a file to read and print to the terminal what is in the files.

The open and write system calls work fine, if I cat the files they display exactly what they should. When I try to read from the files though my reads are always returning 0, and so not displaying anything from the file.

I tried running the program once, then commenting out the write function. When I do this the read function will read from the files, but the output is unfortunately garbage. I seem to have this sort of trouble when using the read system call and would very much appreciate any help so I can use them properly.

Here are the open and read functions, I have code in the read function to check the values of the fd that the pointers hold and they are correct.

Code:

int openfiles(int *fdp1, int *fdp2, int *fdp3){

	/*Open file for appending */
	if((*fdp1=open("file1-append", O_RDWR|O_CREAT|O_APPEND,S_IRUSR |S_IWUSR))==-1){
		perror("File1 Open Error");
	}
	
	/* open file and truncate */
	if((*fdp2=open("file2-trunc", O_RDWR|O_CREAT|O_TRUNC, S_IRUSR|S_IWUSR))==-1){
		perror("File2 Open Error");	
	}
	
	/* Open file only if it does not already exist */
	if((*fdp3=open("file3-wronce", O_RDWR|O_CREAT|O_EXCL, S_IRUSR|S_IWUSR))==-1){
		perror("File3 Open Error");
	}

return 0;

}

int readfiles(int *fdp1, int *fdp2, int *fdp3){
	printf("\nfdp1:%d,fdp2:%d,fdp3:%d\n",*fdp1,*fdp2,*fdp3);
	ssize_t readstatus;	
	char mybuffer[BUFF_SIZE];
	
	
	
	puts("File 1:");
	readstatus = read(*fdp1,&mybuffer,BUFF_SIZE);
	printf("\nreadstatus:%d\n",readstatus);
	while(readstatus > 0){
		puts(mybuffer);
		printf("\nreadstatus:%d\n",readstatus);
		readstatus = read(*fdp1,&mybuffer,BUFF_SIZE);
	}
	printf("\nreadstatus:%d\n",readstatus);
	if(readstatus ==-1){
		perror("Error reading File 1:");
		exit(1);
	}
	

	
	if((readstatus = read(*fdp2,&mybuffer,BUFF_SIZE))==-1){
		perror("Error reading File 2:");
		exit(1);
	}
	printf("\nreadstatus:%d\n",readstatus);
	puts("File 2:");
	puts(mybuffer);
	if((readstatus = read(*fdp3,&mybuffer,BUFF_SIZE))==-1){
		perror("Error reading File 3:");
		puts("File probably already exists");	
	}
	puts("File 3:");
	puts(mybuffer);

	return 0;

}