我无法将optarg分配给inFilename
和outFilename
。该错误表明发生了不兼容的类型错误。如果这是一个微不足道的错误,请原谅我,我已经在一周前开始学习C.
编辑:以下是我打算如何使用它:
./ sortfile -i input.txt -o output.txt
int main(int argc, char *argv[]) {
char c;
const int MAX_FILENAME_LEN = 256;
const int MAX_NUMBERS = 100;
int xFlag = 0;
int yFlag = 0;
char inFilename[MAX_FILENAME_LEN];
char outFilename[MAX_FILENAME_LEN];
int *numbers; // number array: to be dynamically allocated
int count;
int exitValue = 1;
//printf("Enter the input file name: ");
//scanf("%s", inFilename);
while ((c = getopt(argc, argv, "ioxy")) != -1) {
switch (c) {
case 'i':
strncpy(inFilename, optarg, sizeof(inFilename) - 1);
break;
case 'o':
strncpy(outFilename, optarg, sizeof(outFilename) - 1);
break;
case 'x':
xFlag = 1;
break;
case 'y':
yFlag = 1;
break;
case '?':
fprintf(stderr, "Unrecognized option!\n");
break;
}
}
if (!inFilename || !outFilename) {
fprintf(stderr, "Must have -i and -o option!\n");
exit(0);
}
numbers = (int *) malloc(MAX_NUMBERS * sizeof(int));
count = readNumbers(numbers, inFilename);
if (count >= 0) {
//printf("Enter the output file name (will be created/overwitten): ");
//scanf("%s", outFilename);
printArray(numbers, count);
bubbleSort(numbers, count, true);
printArray(numbers, count);
writeNumbers(numbers, count, outFilename);
}
free(numbers);
return exitValue;
}
以下是更改前的程序。这个程序有效。
int main(void) {
const int MAX_FILENAME_LEN = 256;
const int MAX_NUMBERS = 100;
char inFilename[MAX_FILENAME_LEN];
char outFilename[MAX_FILENAME_LEN];
int *numbers; // number array: to be dynamically allocated
int count;
int exitValue = 1;
printf("Enter the input file name: ");
scanf("%s", inFilename);
numbers = (int *) malloc(MAX_NUMBERS * sizeof(int));
count = readNumbers(numbers, inFilename);
if (count >= 0) {
printf("Enter the output file name (will be created/overwitten): ");
scanf("%s", outFilename);
printArray(numbers, count);
bubbleSort(numbers, count, true);
printArray(numbers, count);
writeNumbers(numbers, count, outFilename);
exitValue = 0;
}
free(numbers);
return exitValue;
}
答案 0 :(得分:3)
此:
getopt(argc, argv, "ioxy")
告诉getopt()
四个选项,i
,o
,x
和y
,其中没有一个选择参数。这就是为什么从optarg
获取这些参数的任何尝试都失败了,因为它们不存在。
您需要的是:
getopt(argc, argv, "i:o:xy")
告诉getopt()
您的i
和o
选项应该有参数