You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C语言程序fgets()函数未执行问题排查

问题根因

你遇到的问题是3处C语言基础语法/逻辑错误导致的,具体如下:

  • 输入缓冲区残留换行符:选择模式时你用fgets(selection, 2, stdin)读取输入,selection长度仅为2,fgets最多读取1个有效字符+1个字符串结束符,用户输入模式字符后敲的回车(\n)会留在输入缓冲区里。后续代码执行到写文件逻辑的第一个fgets时,会直接读到这个残留的换行符,导致循环判断条件str[0] != '\n'直接不成立,循环体完全不运行,看起来就像if块后续代码没执行。
  • 字符串比较方式错误:C语言中不能直接用!=/==比较字符串内容,你写的if (mode != "r")本质是比较mode数组的栈内存地址和字符串常量"r"的只读数据段地址,不是比较两个字符串的内容,这个判断逻辑本身是无效的,比较字符串内容必须用strcmp函数。
  • fprintf用法完全错误:fprintf的第一个参数是目标文件指针,第二个参数是格式字符串,你写的fprintf(str, 200, file_ptr)参数顺序、参数类型全错,就算前面逻辑走通,执行到这行也会触发内存访问崩溃。你要实现把输入的字符串写入文件,应该用fputs(str, file_ptr)。
  • 额外隐患:没有处理fopen失败的分支,如果文件打开失败返回NULL,后续直接执行fclose会触发空指针崩溃;另外读模式下没有实现读取文件内容输出的逻辑。
修正后可运行代码
#define _CRT_SECURE_NO_WARNINGS

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
// #include "bsp10048.h" // 本地自定义头文件,通用编译时可注释
#include <string.h>
#define MAX_EINGABE 80


/*----- Dateiöffner und Editor -----*/


int main(void)
{
    FILE* file_ptr;
    char str[200], selection[3], mode[3], name[200]; // 调整数组长度避免越界
    int repeat = 1; 
    int c; // 用于清空输入缓冲区残留字符

    printf("\nPlease enter filename: ");
    fgets(name, 200, stdin);
    name[strcspn(name, "\n")] = 0;
    strcat(name, ".txt");

    printf("\n'r' = Read-mode (Open file for reading)");
    printf("\n'w' = Write-mode (Create file for writing)");
    printf("\n'a' = Append-mode (Open file for appending)");
    
    /*MODE SELECTION*/
    while (repeat) {
        printf("\n\nBitte Modus waehlen: ");
        fgets(selection, 3, stdin);
        // 清空缓冲区残留,避免影响后续输入逻辑
        while((c = getchar()) != '\n' && c != EOF);
        
        switch (selection[0]) {
        case 'r':
            strcpy(mode, "r");
            printf("\nRead-mode selected\n");
            repeat = 0;
            break;
        
        case 'w':
            strcpy(mode, "w");
            printf("\nWrite-mode selected\n");
            repeat = 0;
            break;
        
        case 'a':
            strcpy(mode, "a");
            printf("\nAppend-mode selected\n");
            repeat = 0;
            break;

        default:
            printf("\nInvalid mode!");
            break;
        }
    }

    file_ptr = fopen(name, mode);
    if (file_ptr == NULL) {
        printf("Failed to open file!\n");
        return 1;
    }
    printf("File successfully opened!\n");

    // 用strcmp比较字符串内容
    if (strcmp(mode, "r") == 0) {
        // 读模式:逐行读取文件内容输出
        printf("\n--- File content start ---\n");
        while (fgets(str, 200, file_ptr) != NULL) {
            printf("%s", str);
        }
        printf("\n--- File content end ---\n");
    } else {
        // 写/追加模式:读取用户输入写入文件,输入空行结束
        printf("\nPlease enter content to write, input empty line to finish:\n");
        fgets(str, 200, stdin);
        while (str[0] != '\n') {
            fputs(str, file_ptr);
            fgets(str, 200, stdin);
        }
    }

    fclose(file_ptr);
    return 0;
}

内容的提问来源于stack exchange,提问作者snakepliskin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.03 02:24:21