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

C语言凯撒加密开发中openFile函数打开文件报错求助

凯撒加密程序文件打开错误排查

时隔两年重拾C语言,开发凯撒加密程序时,调用openFile函数打开文件出现错误。


相关代码

加密及文件操作模块

// 字符加密函数
char encrypt(char c, int jump) {
    int overflow = 0;
    char res = c;
    char tabChars[26] = {'a','b','c','d','e','f','g','h',
                   'i','j','k','l','m','n','o','p','q',
                   'r','s','t','u','v','w','x','y','z'};

    for(int i=0;i<sizeof(tabChars);i++) {
        if(c == tabChars[i]) {
            if(i+jump > 25) {
                overflow = i+jump - 26;
                res = tabChars[overflow];
            } else if(i+jump <= 25) {
                res = tabChars[i+jump];
            }
        }
    }
    return res;
};

void writeInFile(FILE* file) {
    //todo
};

// 错误发生在这里
void openFile(char* file) {
    FILE* f = fopen(file, "r");
    printf("\nopen file : %s\n", file);
    char c;
    while((c = getc(f)) != EOF) {
        putchar(c);
    }
    fclose(f);
};

主函数代码

int jump = 5;
char c = 't';
printf("\nletter change with : --%c--\n",encrypt(c,jump));

char* file = "taget/to/message.txt";
openFile(file); // 错误发生在这里

报错信息

Invalid parameter passed to C runtime function.
Invalid parameter passed to C runtime function.

问题原因

  1. 文件路径拼写错误:你指定的路径是"taget/to/message.txt",其中taget是拼写错误,正确应为target。路径错误会导致fopen无法找到文件,返回NULL指针。
  2. 未检查文件打开状态:代码中直接使用fopen返回的指针,没有判断是否打开成功。当f为NULL时,后续调用getc(f)和fclose(f)都会传递无效参数给C运行时函数,触发报错。
  3. getc返回值类型错误:getc返回int类型(包含EOF这个超出char范围的值),你用char接收会导致无法正确判断EOF,甚至可能引发额外的未定义行为。

修正方案

  1. 修正文件路径的拼写错误,确保目标文件存在于指定路径下;
  2. 在openFile函数中添加文件打开成功的检查,同时修正getc的接收类型:
void openFile(char* file) {
    FILE* f = fopen(file, "r");
    // 检查文件是否打开成功
    if (f == NULL) {
        perror("文件打开失败");
        return;
    }
    printf("\nopen file : %s\n", file);
    int c; // 用int接收getc的返回值
    while((c = getc(f)) != EOF) {
        putchar(c);
    }
    fclose(f);
};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 20:06:19