我想寫我自己版本的head
Unix命令,但是我的程序不工作。如何使用Unix系統調用打印文本文件的前10行?
我試圖打印文本文件的前10行,而是程序打印所有行。我通過命令行參數指定要打印的文件名和行數。我只需要使用Unix系統調用,如read()
,open()
和close()
。
下面是代碼:
#include "stdlib.h"
#include "stdio.h"
#include <fcntl.h>
#include <stdlib.h>
#include <unistd.h>
#define BUFFERSZ 256
#define LINES 10
void fileError(char*, char*);
int main(int ac, char* args[])
{
char buffer[BUFFERSZ];
int linesToRead = LINES;
int in_fd, rd_chars;
// check for invalid argument count
if (ac < 2 || ac > 3)
{
printf("usage: head FILE [n]\n");
exit(1);
}
// check for n
if (ac == 3)
linesToRead = atoi(args[2]);
// attempt to open the file
if ((in_fd = open(args[1], O_RDONLY)) == -1)
fileError("Cannot open ", args[1]);
int lineCount = 0;
//count no. of lines inside file
while (read(in_fd, buffer, 1) == 1)
{
if (*buffer == '\n')
{
lineCount++;
}
}
lineCount = lineCount+1;
printf("Linecount: %i\n", lineCount);
int Starting = 0, xline = 0;
// xline = totallines - requiredlines
xline = lineCount - linesToRead;
printf("xline: %i \n\n",xline);
if (xline < 0)
xline = 0;
// count for no. of line to print
int printStop = lineCount - xline;
printf("printstop: %i \n\n",printStop);
if ((in_fd = open(args[1], O_RDONLY)) == -1)
fileError("Cannot open ", args[1]);
//read and print till required number
while (Starting != printStop) {
read(in_fd, buffer, BUFFERSZ);
Starting++; //increment starting
}
//read(in_fd, buffer, BUFFERSZ);
printf("%s \n", buffer);
if (close(in_fd) == -1)
fileError("Error closing files", "");
return 0;
}
void fileError(char* s1, char* s2)
{
fprintf(stderr, "Error: %s ", s1);
perror(s2);
exit(1);
}
我在做什麼錯?
輕微:爲什麼在'int main(int ac,char * args [])'中使用'ac,args'而不是常見的'argc,argv'? – chux
查看源代碼:https://github.com/goj/coreutils/blob/rm-d/src/head.c – xxfelixxx
在fileError中,對'perror'的調用是錯誤的。 fprintf可能已經修改了errno,你會得到一個意外的結果。 –