gpt4 book ai didi

c - 使用 getopt() 时无法分配 optarg

转载 作者:太空宇宙 更新时间:2023-11-04 07:13:44 25 4
gpt4 key购买 nike

我无法将 optarg 分配给 inFilenameoutFilename。该错误表明发生了不兼容的类型错误。如果这是一个小错误,请原谅我,我大约一周前开始学习 C。

编辑:我使用过 strncpy 但出现段错误。

编辑:这是我打算如何使用它:

./sortfile -i 输入.txt -o 输出.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;

最佳答案

这个:

getopt(argc, argv, "ioxy")

告诉 getopt() 四个选项,ioxy,它们都不带参数。这就是为什么从 optarg 获取这些参数的任何尝试都失败了,因为它们不存在。

你需要的是:

getopt(argc, argv, "i:o:xy")

告诉 getopt() 你的 io 选项应该有参数

关于c - 使用 getopt() 时无法分配 optarg,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26500183/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com