【发布时间】:2021-08-16 06:43:46
【问题描述】:
我正在用 C 语言编写一个 cat 命令克隆,当我更改选项标志的顺序时出现了奇怪的行为。
-s 选项标志压缩双倍行距。
-n 选项标志编号从 1 开始的每一行。
我已经通过以下方式检查了运行我的程序的区别:
$ diff <(./myCat -s spaces.txt) <(cat -s spaces.txt)
no difference
$ diff <(./myCat -n spaces.txt) <(cat -n spaces.txt)
no difference
$ diff <(./myCat -ns spaces.txt) <(cat -ns spaces.txt)
no difference
但是,运行./myCat -sn spaces.txt 只会压缩文本,不会对行编号。
谁能解释这种行为?我认为在这种情况下选项标志的顺序无关紧要。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
int main(int argc, char **argv) {
FILE *fp;
const int bufferSize = 4096;
char buffer[bufferSize];
int currentFile = 0;
for (int i = 1; i < argc; i++) {
if (argv[i][0] != '-') {
currentFile = i;
break;
}
}
int bflag = 0, eflag = 0, nflag = 0, sflag = 0;
int opt;
while ((opt = getopt(argc, argv, "bens:?")) != -1) {
switch(opt) {
case 'b':
bflag++;
break;
case 'e':
eflag++;
break;
case 'n':
nflag++;
break;
case 's':
sflag++;
break;
case ':':
printf("option needs a value\n");
exit(1);
case '?':
printf("usage: cat [-bens] [file ...]\n");
exit(1);
}
}
while (currentFile < argc) {
if (currentFile) {
fp = fopen(argv[currentFile], "rb");
if (fp == NULL) {
fprintf(stderr, "%s: %s: No such file or directory",
argv[0], argv[currentFile]);
exit(1);
}
}
int lineNumber = 1;
int lastLineBlank = 0;
while (fgets(buffer, bufferSize, (fp == NULL ? stdin : fp))) {
int length = strlen(buffer);
buffer[length - 1] = '\0';
if (sflag) {
length = strlen(buffer);
int currentLineBlank = (length <= 1) ? 1 : 0;
if (lastLineBlank && currentLineBlank) {
continue;
}
lastLineBlank = currentLineBlank;
}
if (bflag) {
length = strlen(buffer);
if (length >= 1) {
char *tmp = strdup(buffer);
buffer[0] = '\0';
sprintf(buffer, "%*d\t", 6, lineNumber++);
strcat(buffer, tmp);
}
} else
if (nflag) {
char *tmp = strdup(buffer);
buffer[0] = '\0';
sprintf(buffer, "%*d\t", 6, lineNumber++);
strcat(buffer, tmp);
}
if (eflag) {
length = strlen(buffer);
buffer[length] = '$';
buffer[length + 1] = '\0';
}
fprintf(stdout, "%s\n", buffer);
}
fclose(fp);
currentFile++;
}
return 0;
}
【问题讨论】: