Created
March 15, 2018 16:55
-
-
Save cubedtear/9159db7df7d6a7e00223c7ab0636a2ab to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Group members: | |
// | |
// - Iñigo Arnedo | |
// - Elena Hernandez | |
// - Aritz Lopez | |
// - Ane Odriozola | |
#include <stdio.h> | |
#include <unistd.h> | |
#include <termios.h> | |
#define TRUE 1 | |
#define FALSE 0 | |
int one_page(FILE* fd, int max) // Writes one page | |
{ | |
int c; | |
int n = 0; | |
while (n < max && (c = getc(fd)) != EOF) { | |
putc(c, stdout); | |
if (c == '\n') n++; | |
} | |
return n; | |
} | |
int one_line(FILE* fd) // Writes one line | |
{ | |
int c = 0; // Can be anything except '\n' | |
// write chars while its not EOF and last char was not newline | |
while (c != '\n' && (c = getc(fd)) != EOF) putc(c, stdout); | |
return c == '\n'; // returns 1 if last char was '\n' => one line was written | |
} | |
void setRaw(int echo) | |
{ | |
struct termios t; | |
tcgetattr(STDIN_FILENO, &t); //get the current terminal I/O structure | |
if (echo) t.c_lflag &= ~(ICANON | ECHO); | |
else t.c_lflag |= ICANON | ECHO; | |
tcsetattr(STDIN_FILENO, TCSANOW, &t); //Apply the new settings | |
} | |
int main(int argc, char *argv[]) { | |
if (argc != 2 && argc != 3) | |
{ | |
fprintf(stderr, "Usage: %s filename [page_size]\n", argv[0]); | |
return 1; | |
} | |
int pageSize = 24; | |
if (argc == 3) pageSize = atoi(argv[2]); | |
if (pageSize < 1) { | |
fprintf(stderr, "error: page_size must be a positive number!"); | |
return 2; | |
} | |
FILE* f = fopen(argv[1], "r"); | |
if (f == NULL) | |
{ | |
perror(argv[1]); | |
return 3; | |
} | |
setRaw(TRUE); | |
int l = one_page(f, pageSize) == pageSize; | |
while (l) | |
{ | |
char c; | |
// getc returns EOF when end of file has reached or an error occurred | |
if ((c = getc(stdin)) == EOF) | |
{ | |
// If an error has occured | |
if (ferror(f)) | |
{ | |
perror(argv[1]); | |
fclose(f); | |
setRaw(FALSE); | |
return 4; | |
} | |
break; | |
} | |
// The next line is to check if the Down Arrow has been | |
// pressed (not asked, so not implemented, but tested :P) | |
// | |
// c == 27 && getc(stdin) == 91 && getc(stdin) == 'B' | |
if (c == '\n') // Enter = one line more | |
{ | |
l = one_line(f) == 1; | |
} | |
else if (c == ' ') // Space = one page more | |
{ | |
l = one_page(f, pageSize) == pageSize; | |
} | |
else if (c == 'q') break; // q = quit | |
} | |
fclose(f); | |
setRaw(FALSE); | |
return 0; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment