在对 fgets 进行不相关的函数调用后,字符数组被清除了吗?

Char array being cleared after unrelated function call to fgets?

我正在为 C 项目创建一个文件管理程序,我遇到了这个错误,这对大多数程序员来说可能是显而易见的,但由于我真的很糟糕,所以我无法发现我做错了什么。我的主程序是一个界面,它要求用户输入文件名并将其分配给数组 fileName.

int main() {
    char fileName[50];
    assignFileName(fileName);
    char option[2];
    int checkInput;
    do {
        printf("File management program. Options :\n '1' for File operations (Create, copy, delete or display file)\n '2' for Line operations (Append, delete, display or insert line to file)\n '3' for General operations (Display change log or number of lines for file)\n '4' to select a new file\n '9' to exit program\n");
        printf("aaa %s\n", fileName); //first printf check - prints "aaa" and value in fileName
        checkInput = checkUserInput(option);
        printf("aaa %s\n", fileName); // second printf check = prints only "aaa"
        if (checkInput == 1) {
          //... etc
        }
void assignFileName(char *fileName) {
    printf("Enter file name to operate on, or 'E' to exit the program.\n");
    do {
        if ((fgets(fileName, 50, stdin)) != NULL) {
            if (fileName[strlen(fileName)-1] = '\n') {
                fileName[strlen(fileName)-1] = '[=11=]'; 
            }
            if (strlen(fileName) == 1 && *fileName == 'E') {
                exit(0);
            } else if (strlen(fileName) == 0) {
                printf("Error : Please enter a file name or 'E' to exit.\n");
            }
        } else {
            perror("Error assigning file name ");
        }
        
    } while (strlen(fileName) == 0);
}

我很确定这段代码没问题。可能有很多方法可以提高效率,如果有人想提供意见,我会考虑的。但是,问题稍后出现在代码中。我有 2 个 printf 语句来检查文件名的值。在第一个之后,一切似乎都很好,但是对于第二个,fileName 的值似乎被清除了,所以在 checkUserInput 中显然发生了一些事情。 checkUserInput 所做的只是检查用户是否输入了一个数字:

void flush() {
    int ch;
    while ((ch = getchar()) != '\n' && ch != EOF) {
    }
}

int checkUserInput(char *input) {
    if (fgets(input, 3, stdin) != NULL) {
        printf("you entered %c\n", input[0]);
        if (input[1] == '\n') {
            return 1;
        } else {
            flush();
            printf("Error : Please enter one of the options given.\n");
        }
    } else {
        printf("Error : Please try again.\n");
    }
    return 0; 
}

我将更多 printf 语句用于错误检查,似乎在调用 fgets(input, 3, stdin) 后,fileName 中的值被清除。谁能向我解释为什么会这样?我什至没有将数组 fileName 传递给 checkUserInput,所以我什至不知道程序是如何改变它的。这是控制台显示的 link:(不能 post 图片抱歉,不是 10 rep)。 https://cdn.discordapp.com/attachments/708320229737889832/802557193043050516/unknown.png

所有帮助将不胜感激。谢谢。

if (fileName[strlen(fileName)-1] = '\n') 应该是:

if (fileName[strlen(fileName)-1] == '\n') 

请注意,您可以使用以下简单的行去除尾随的换行符:

filename[strcspn(filename, "\n")] = '[=11=]';

错误是 char option[2],而它应该是 char option[3]。感谢@Nate Eldredge 和@M Oehm