[Beds] Programming

David Pashley david at davidpashley.com
Fri Jan 27 22:20:11 GMT 2006


On Jan 27, 2006 at 19:00, Stephen Elliott praised the llamas by saying:
> Hi,
> 
> I have a C program here which a friend has sent me and I am trying to
> understand. I did basic C programming when I was at college and wrote quite
> a nice Shipbourne radar system, but this one blows me.
> 
> It uses pointers and I understand the principle behind them. I was wondering
> if someone could explain the code to me, the line I am having the most
> trouble with is the calloc line.
> 

It's worth pointing out this is really bad C, but lets go through it:

 | #include <fcntl.h> 

 have no idea why this is imported. You want unistd.h (for read) and
 stdio.h (for printf). 
 | 
 | main() 

Start the main() function. This should really be "int main(void)" or
"int main(int argc, char *argv[])".
 | { 
 | 
 | char *c; int fd, sz; c = (char *) calloc(100, sizeof(char)); 

Defines a dynamic character array, and two integers (fd and sz) and then
allocates memory for 100 chars.

 | fd = open("in1", O_RDONLY); 
 | 
Open a file called in1 for reading.
 
 | 	if (fd < 0) 
 | 	{ 
 | 		perror("r1"); 
 | 		exit(1); 
 | 	} 
 | 
Check for errors opening the file.
 
 | sz = read(fd, c, 10); 

Read 10 bytes from the file and put the number of bytes read into sz.
 
 | printf("called read(%d, c, 10). returned that %d bytes were read.\n", fd, sz); 

Output how many bytes were read.

 | c[sz] = '\0';
 | 
Null terminate the current end of the string so we can output it.
 
 | printf("Those bytes are as follows: %s\n", c); 
 | 
Output the bytes read.
 
 | sz = read(fd, c, 99); 
 | 
Read in 99 bytes.
 
 | printf("called read(%d, c, 99). returned that %d bytes were read.\n",fd, sz); 
 | 
Again print out how many bytes we read.
 
 | c[sz] = '\0'; 

null-terminate the string again

 | printf("Those bytes are as follows: %s\n", c); 

print out those bytes.

 | close(fd);

Close the file.

 | } 

End of the function and program.

-- 
David Pashley
david at davidpashley.com
Nihil curo de ista tua stulta superstitione.



More information about the Beds mailing list