我想为我正在构建的用户定义的shell实现cat
或more
样式命令。
我想添加的扭曲是允许用户按空格键打印下一个x行。
所以我有以下代码打印出整个char缓冲区......
int user_more(char argc, char *argv){
char buf[64];
FILE *file;
size_t nread;
file = fopen("test.txt", "r");
if (file) {
while ((nread = fread(buf, 1, sizeof buf, file)) > 0)
fwrite(buf, 1, nread, stdout);
if (ferror(file)) {
/* deal with error */
printf("There was an error opening your file. Please check the name and try again.\n");
}
fclose(file);
}
}
因此,为了澄清,我想首先打印出第一个x行,然后在用户按空格键后,我想打印出下一个x行。
**
**
此实现要求用户输入n因为我无法使用conio.h库(用户箭头键)
while (1){
//print out first four lines
if (j == 1){
for (i = 0; i < 4; i++){
fgets(buf, sizeof(buf), file);
printf("%s", buf);
}
j++;
}
scanf(" %c", &next);
if (next == 'n'){
//spacebear has been pressed
//loop +4 times and only print the last 4 lines
for (i = 0; i < k; i++){
fgets(buf, sizeof(buf), file);
if (i == k-4 || i == k-3 || i == k-2 || i == k-1){
printf("%s", buf);
}
}
k += 4;
}
}