ch2-readfile
Chapter_2 chown | test |
readfile.c ALP, p. 42-43
#include <stdio.h> // for printf(), NULL
#include <stddef.h> // for size_t, ssize_t
#include <stdlib.h> // for malloc(), free()
#include <fcntl.h> // for open(), O_RDONLY
#include <unistd.h> // read(), close()
#define LENGTH 100
char * read_from_file (const char * filename, size_t length);
int main()
{
char *s = read_from_file("readfile.c", LENGTH);
if (s != NULL)
{printf("%s\n", s);}
return 0;
}
char * read_from_file (const char * filename, size_t length)
{
char *buffer;
int fd; // file descriptor
ssize_t bytes_read;
buffer = (char*) malloc (length); /* Allocate the buffer. */
if (buffer == NULL)
{return NULL;}
fd = open (filename, O_RDONLY); /* Open the file for reading. */
if (fd == -1)
{ /* open() failed. Deallocate buffer before returning. */
free (buffer);
return NULL;
}
bytes_read = read (fd, buffer, length); /* Read the data. */
// bytes_read <= length if read() reaches the end of file
// bytes_read == 0 if reading starts at the end of file
if (bytes_read <= 0) // read failed
{ // bytes_read < 0 on error
free (buffer); // Deallocate buffer and
close (fd); // close fd
return NULL; // before returning
}
/* Everything's fine. Close the file and return the buffer. */
close (fd);
return buffer;
}
/*
gcc readfile.c -o readfile
./readfile
#include <stdio.h> // for printf(), NULL // 41 chars with '\n'
#include <stddef.h> // for size_t, ssize_t // 43 chars with '\n'
#include <stdlib // 16 chars, 100 in total
*/
Chapter_2 chown | BACK_TO_TOP | test |
Comments
Post a Comment