【问题标题】:Implementing the tail command in C by printing out the last 10 lines using low-level system calls通过使用低级系统调用打印出最后 10 行,在 C 中实现 tail 命令
【发布时间】:2022-11-04 01:25:08
【问题描述】:

我正在尝试用 C 语言编写一个程序,该程序使用低级系统调用来复制 tail 命令,默认情况下,该命令将打印出作为参数传递的文件的最后 10 行。

每次我尝试运行 ./tail [FILENAME] 时,都没有打印任何内容。这是我到目前为止写的:

#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <fcntl.h>

#define LINES_TO_READ 10
#define BUFF_SIZE 1024 * 1024

int main(int argc, char *argv[]) {
  int fd=open(argv[1], O_RDONLY);
  int k;
  char c;
  char buff[BUFF_SIZE];
  int r;
  int l;
  int counter;
  //char buffer[BUFF_SIZE];
  while((k = read(fd, buff, 1)) != 0) {
    if (fd < 0) {
            perror("open");
            return -1;
        } //read file
    if(c == '\n') {
      counter++;
    }
     l = lseek(fd, LINES_TO_READ, SEEK_END);
     r = read(fd, &c, l);
    if (r < 0) {
                perror("read");
                return -1;
             }
   
  }
   write(1, buff, r); 

}

我错过了什么/做错了什么?任何帮助将不胜感激。

【问题讨论】:

    标签: c unix system-calls


    【解决方案1】:

    你至少有以下问题:

    • 您在此处使用cif(c == ' '),但您从未将任何内容分配给c
    • 你永远不会初始化counter,在C语言中局部变量默认不初始化为0,它们可以包含任何东西。
    • 您检查if (fd &lt; 0) 太晚了,您需要在第一次尝试读取它之前进行此检查。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-06-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-03
      • 2013-01-20
      • 1970-01-01
      相关资源
      最近更新 更多