【发布时间】:2019-04-06 22:39:03
【问题描述】:
我正在执行 cat linux 命令。目前,它可以从标准输入中读取,当在命令之后没有传递任何参数并从多个文件中顺序读取时.
例如,如果您将 -file1.txt -file2.txt - 作为参数传递,那么一切都会按预期工作。它从标准输入读取,输出 file1.txt 的内容,再次从标准输入读取等等。但是如果我删除第一个'-',换句话说,如果第一个参数是一个文件,它会输出 file1.txt 的内容,然后从标准输入读取,然后打印第二个文件的内容,然后,而不是读取从 stdin 像以前一样,它第一次从 stdin 读取它再次输出第二个文件的内容,然后是输入,之后它才开始正常运行。
代码如下:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define BUF_SIZE 1024
void readStdin(){
char buffer[BUF_SIZE];
while(fgets(buffer, BUF_SIZE, stdin)){ //reads from the standard input and prints the input
char *content = malloc(sizeof(char*)*BUF_SIZE);
if(content == NULL){ //failed to allocate memory
exit(1);
}
strcat(content, buffer);
//printf("buffer: %s", buffer);
//printf("content: %s", content);
printf(content);
memset(&content[0], 0, sizeof(*content));
free(content);
//printf("bufferEND: %s", buffer);
//printf("contentEND: %s", content);
}
}
void readArgs(int argc, char* argv[]){
FILE* fp;
char ch;
for (int i=1; i<argc; i++){
if (*argv[i] == '-'){
readStdin();
clearerr(stdin);
}
//else if ()
else {
fp = fopen(argv[i], "r");
if (fp==NULL){ //in case the file doesn't exist
printf("%s: No such file or directory\n", argv[i]);
exit(1);
}
while ((ch=fgetc(fp)) != EOF){
putchar(ch);
}
// fflush(stdin);
fclose(fp);
}
}
}
int main(int argc, char* argv[]){
if (argc<2){
readStdin();
return 0;
}
readArgs(argc, argv);
return 0;
}
有什么提示吗?
编辑:如果我传递另一个文件后跟另一个'-',在以上述错误方式从标准输入读取后,它不仅行为相同,而且不打印前一个输出的第一个字符
【问题讨论】: