mirror of
https://github.com/BoredDevNL/BoredOS.git
synced 2026-05-15 18:58:40 +00:00
Update tail command to read from the front of the file
This commit is contained in:
parent
c253ee0480
commit
09840e522a
1 changed files with 8 additions and 22 deletions
|
|
@ -6,13 +6,13 @@
|
||||||
#include <stdlib.h>
|
#include <stdlib.h>
|
||||||
|
|
||||||
int main(int argc, char *argv[]) {
|
int main(int argc, char *argv[]) {
|
||||||
// print all lines
|
|
||||||
if (argc == 2) {
|
if (argc == 2) {
|
||||||
if(strcmp(argv[1], "--help")) {
|
if (strcmp(argv[1], "--help") == 0) {
|
||||||
printf("-This command reads from the back of the file\n");
|
printf("-This command reads from the front of the file\n");
|
||||||
printf("-Use: tail [-n] [-number of lines] [file]\n");
|
printf("-Use: tail [-n] [-number of lines] [file]\n");
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
|
//print everything
|
||||||
FILE *fp = fopen(argv[1], "r");
|
FILE *fp = fopen(argv[1], "r");
|
||||||
if (fp == NULL) {
|
if (fp == NULL) {
|
||||||
printf("File not found\n");
|
printf("File not found\n");
|
||||||
|
|
@ -25,11 +25,11 @@ int main(int argc, char *argv[]) {
|
||||||
fclose(fp);
|
fclose(fp);
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
// only print last lines
|
// only print first lines
|
||||||
if (argc == 4 && strcmp(argv[1], "-n") == 0) {
|
if (argc == 4 && strcmp(argv[1], "-n") == 0) {
|
||||||
int lines = atoi(argv[2]);
|
int lines = atoi(argv[2]);
|
||||||
if (lines <= 0) {
|
if (lines <= 0) {
|
||||||
printf("Number of lines should be positive\n");
|
printf("Number of lines must be positive\n");
|
||||||
return 1;
|
return 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -39,24 +39,10 @@ int main(int argc, char *argv[]) {
|
||||||
return 1;
|
return 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
// count total lines
|
|
||||||
int count = 0;
|
|
||||||
char buf[1024];
|
char buf[1024];
|
||||||
while (fgets(buf, sizeof(buf), fp)) {
|
while (lines > 0 && fgets(buf, sizeof(buf), fp)) {
|
||||||
count++;
|
|
||||||
}
|
|
||||||
|
|
||||||
// back to start of file
|
|
||||||
fseek(fp, 0, SEEK_SET);
|
|
||||||
|
|
||||||
// check if lines are the end lines
|
|
||||||
int skip = count - lines;
|
|
||||||
int i = 0;
|
|
||||||
while (fgets(buf, sizeof(buf), fp)) {
|
|
||||||
if (i >= skip) {
|
|
||||||
printf("%s", buf);
|
printf("%s", buf);
|
||||||
}
|
lines--;
|
||||||
i++;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fclose(fp);
|
fclose(fp);
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue