I am trying to write a program in C (for xv6) that returns the last "n" number of lines of input text or a file (essentially tail) with the exception that it should not print blank lines("\n"). At the moment, my code is able to correctly ignore blank lines, but it will still print a blank line if the first line to be printed is a blank line.
For example, this is my output if only 2 lines are to be printed:
\n (a blank space)
the quick brown fox jumped over the lazy dog
But the output should look like:
the quick brown fox jumped over the lazy dog
Things I have tried:
I feel like the solution is simple, but I can't figure it out. Does anybody have any ideas?
edit - provided full code
#include "types.h"
#include "stat.h"
#include "user.h"
#include "fcntl.h"
char buf [1024];
void tail (int fd, char* name, int lines){
int chunk_index; //keeps track of the chunk index
int chunk_size; //keeps track of the size of the chunk
int lines_in_doc = 0; //keeps track of the total number of lines
int current_line_num = 0; //keeps track of the character count in each chunk
int temp_line = open("temporary_file", O_CREATE | O_RDWR);
while ((chunk_size = read(fd, buf, sizeof(buf))) > 0){
write(temp_line, buf, chunk_size);
for (chunk_index = 0; chunk_index <= chunk_size; chunk_index++){
if (buf[chunk_index] != '\n'){
continue;
}else{
lines_in_doc++;
}
}
}
close(temp_line);
if (chunk_size < 0){
printf(1, "tail - read error \n");
exit();
}
//int total_chunks_read = 0;
temp_line = open("temporary_file", 0);
while((chunk_size = read(temp_line, buf, sizeof(buf))) > 0){
for (chunk_index = 0; chunk_index < chunk_size; chunk_index++){
if (current_line_num >= (lines_in_doc - lines)){
if ((buf[chunk_index] == '\n') && (buf[chunk_index+1] == '\n') && (buf[chunk_index-1] == '\n')){
printf(1,"haha!");
}
else{
printf(1, "%c", buf[chunk_index]);
}
}
else if (buf[chunk_index] == '\n'){
current_line_num++;
}
}
}
close(temp_line);
unlink("temporary_file");
}
//main function
int
main(int argc, char *argv[]){
int i;
int fd = 0;
int x = 10;
char *file;
char a;
file = "";
if (argc <= 1){
tail(0, "", 10);
exit();
} else{
for (i = 1; i < argc; i++){
a = *argv[i];
if (a == '-'){
argv[i]++;
x = atoi(argv[i]++);
}else{
if ((fd = open(argv[i], 0)) < 0){
printf(1, "tail: cannot open %s \n", argv[i]);
exit();
}
}
}
tail(fd, file, x);
close(fd);
exit();
}
}
The requirements for my course's tail assignment was to count, but not print blank lines. So, it would have taken some tinkering of the code of writing to the temporary file which I didn't want to do, since this is not what official tail.c does.
I realized that my logic was missing a component: a blank line between two lines of text would appear as a blankspace, a blankspace, and a non-blankspace. So, I needed to update my if statement to be the following:
if ((buf[chunk_index] == '\n') && (buf[chunk_index + 1] != '\n') &&
(buf[chunk_index - 1] == '\n')) {
printf(1, "");
}