xv6 C 跳过空行

xv6 C skipping blank lines

我正在尝试用 C(对于 xv6)编写一个程序,returns 输入文本或文件(基本上是尾部)的最后“n”行,但它不应该打印空行(“\n”)。目前,我的代码能够正确忽略空行,但如果要打印的第一行是空行,它仍然会打印空行。

例如,如果只打印 2 行,这是我的输出:

\n(空白space)

敏捷的棕色狐狸跳过懒惰的狗

但输出应该如下所示:

敏捷的棕色狐狸跳过懒惰的狗

我尝试过的事情:

我觉得解决方案很简单,但我想不通。有人有什么想法吗?

编辑 - 提供完整代码


#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(); 
    }

}


我课程尾部作业的要求是计数,但不打印 空行。因此,我不想对写入临时文件的代码进行一些修改,因为这不是官方 tail.c 所做的。

我意识到我的逻辑缺少一个组件:两行文本之间的空行将显示为空格、空格和 non-blankspace。所以,我需要更新我的 if 语句如下:

if ((buf[chunk_index] == '\n') && (buf[chunk_index + 1] != '\n') &&
    (buf[chunk_index - 1] == '\n')) {
    printf(1, "");
}