gpt4 book ai didi

c - getopt() 函数表现出奇怪的行为

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

为现有程序的选项参数添加 getopt() 会导致奇怪的行为。

程序接受一个字符串输入,然后从文件中读取单词(每个单词在一个新行上)并检查该字符串是否在文件中。如果是,则将该字符串发送到 Existing.txt 文件,如果不是,它转到 Non-existing.txt。问题在于 getopt() 及其表现出的奇怪行为。(选项是 -n 和 -e 分别更改不存在的文件和现有的文件)

#include <stdio.h>
#include <string.h>
#include <unistd.h>

int main(int argc, char *argv[]) {
char word[80];
char word_in_file[80];
int ch;


FILE *existing = fopen("Existing.txt", "w"); //Open the existing and non_existing file streams
FILE *non_existing = fopen("Non-existent.txt", "w");

while((ch = getopt(argc, argv, "n:e:")) != -1){
switch(ch){
case 'n':
non_existing = fopen(optarg, "w");
break;

case 'e':
existing = fopen(optarg, "w");
break;
default:
fprintf(stderr,"Unknown option argument: %s", optarg);
return 1;
}
argc -= optind;
argv += optind;
}

printf("Enter ZA WARDSU:\n");
while (scanf("%79s[^\n]", &word)) { //Main loop that scans input
if(strcmp(word ,"exit") == 0){
printf("You are now done!\n");
break;
}
FILE *input = fopen(argv[1], "r"); // The stream is initialised here in order to reset it for every loop, the next loop just begins from where it last cut off

while ((fscanf(input, "%79s[^\n]\n", &word_in_file) != EOF)) { // loop that scans the input file
if(strcmp(word_in_file, word) == 0 ){ //if word is in the input file, print it to the existing file
fprintf(existing, "%s\n", word);
break;

}

}
if (strcmp(word, word_in_file) != 0 ) //if word isn't in the input file, print it to the non_existing file
fprintf(non_existing, "%s\n", word); //In main loop because it needs to do this check after it's gone through all the words

}

fclose(existing); //close some data streams
fclose(non_existing);
return 0;
}

所以每当我这样启动它时 - ./check -n Nexname.txt -e Exname.txt inFile.txt 它只是段错误,堆栈转储类似于 Exception: STATUS_ACCESS_VIOLATION at rip=001801C189A

然后我尝试 - ./check -nNexname.txt -eExname.txt inFile.txt。这次它没有崩溃,但它只生成并写入第一个选项的参数文件,第二次它只是写入默认值。

如果我尝试只使用一个这样的选项 - ./check -nNexname.txt inFile.txt,它只会在我输入第一个单词后停止程序。

编辑:当我这样做时它也不会出现段错误 ./check -n Nexname.txt -eExname.txt inFile.txt

有人可以向我解释这种行为的原因(以及如何解决)。

我知道我可以只使用 main 函数 args 来做同样的事情,但我想尝试 getopt() 函数,以便熟悉它。

最佳答案

如果您更好地缩进该代码,则很明显您正在修改 while 循环内的 argvargc 而不是这样做处理完所有选项后一次。

关于c - getopt() 函数表现出奇怪的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54637117/

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