【发布时间】: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