假设你有一个命令行file_matcher 程序,你打算如何使用它?好吧,您必须将文件名传递给要匹配的程序。您不能对它们进行硬编码(意味着您不能在代码文件中写入文件名)。因为如果您对它们进行硬编码,那么您每次都必须更改程序代码中的文件名,如果由于任何原因文件名更改或您想测试新文件。
不管怎样,我给出了一段我很久以前写的代码来匹配两个文件。玩它。并运行它调用它(假设两个文件file_1.txt 和file_2.txt 与file_matcher 在同一个目录中):
> file_matcher file_1.txt file_2.txt
还有file_matcher.c:
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
char *get_charname(int ch) {
if(ch == 0) return "Null";
if(isspace(ch)) return "White space";
if(iscntrl(ch)) return "Control Key";
return "Others";
}
int main(int argc, char *argv[]) {
FILE *f1, *f2;
char ch1, ch2;
int row, col;
if(argc != 3) {
if(argc == 1) printf("Missing file names\n");
else if(argc == 2) printf("Missing a file name\n");
else printf("Too many files\n");
exit(1);
}
f1 = fopen(argv[1], "r");
if(f1 == NULL) {
printf("Error opening \"%s\"\n", argv[1]);
exit(1);
}
f2 = fopen(argv[2], "r");
if(f2 == NULL) {
printf("Error opening \"%s\"\n", argv[2]);
fclose(f1);
exit(1);
}
row = 1;
col = 1;
while(fscanf(f1, "%c", &ch1) != EOF) {
if(fscanf(f2, "%c", &ch2) == EOF) {
printf("Too less data in \"%s\"\n", argv[2]);
printf("Matching stopped at (row, col): (%d, %d)\n", row, col);
fclose(f1);
fclose(f2);
exit(1);
}
if(ch1 != ch2) {
printf("Miss match at (row, col): (%d, %d)\n", row, col);
if(isgraph(ch1)) printf("In \"%s\" found '%c'(ascii value: %d)\n", argv[1], ch1, ch1);
else printf("In \"%s\" found '%s'(ascii value: %d)\n", argv[1], get_charname(ch1), ch1);
if(isgraph(ch2)) printf("In \"%s\" found '%c'(ascii value: %d)\n", argv[2], ch2, ch2);
else printf("In \"%s\" found '%s'(ascii value: %d)\n", argv[2], get_charname(ch2), ch2);
fclose(f1);
fclose(f2);
exit(1);
}
if(ch1 == '\n') {
row++;
col = 1;
}
else col++;
}
if(fscanf(f2, "%c", &ch2) != EOF) {
printf("Too much data in \"%s\"\n", argv[2]);
printf("Matching stopped at (row, col): (%d, %d)\n", row, col);
fclose(f1);
fclose(f2);
exit(1);
}
printf("\"%s\" and \"%s\" matched succesfully\n", argv[1], argv[2]);
fclose(f1);
fclose(f2);
return 0;
}
就像这个程序一样,许多其他程序都被设计为从命令行获取输入...
我希望,现在你明白这背后的原因了....