Skip to content

Instantly share code, notes, and snippets.

Created January 6, 2013 06:22
Show Gist options
  • Select an option

  • Save anonymous/4465610 to your computer and use it in GitHub Desktop.

Select an option

Save anonymous/4465610 to your computer and use it in GitHub Desktop.
C_and_CPP(#1Gw0vUeU)
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#include <stddef.h>
#define READ_BUFFER_SIZE 10
enum FileState
{
FILE_STATE_UNOPENED,
FILE_STATE_READING,
FILE_STATE_ENDREAD,
};
struct File
{
int descriptor;
enum FileState state;
};
void open_file( char const * name,
struct File * file ) {
file->descriptor = open( name, O_RDONLY );
file->state = FILE_STATE_READING;
}
void read_file( struct File * file,
char * buffer, size_t size ) {
if( file->state != FILE_STATE_READING )
return;
int read_bytes = read( file->descriptor,
buffer, size-1 );
if( !read_bytes ) {
file->state = FILE_STATE_ENDREAD;
close( file->descriptor );
}
buffer[ read_bytes ] = '\0';
}
void close_file( struct File * file ) {
if( file->state != FILE_STATE_ENDREAD )
return;
file->state = FILE_STATE_UNOPENED;
close( file->descriptor );
}
int main() {
struct File file;
char read_buffer[ READ_BUFFER_SIZE ];
open_file( "input.txt", &file );
while( read_file(&file, read_buffer, READ_BUFFER_SIZE),
file.state != FILE_STATE_ENDREAD ) {
puts( read_buffer );
}
close_file( &file );
return EXIT_SUCCESS;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment