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

C语言如何实现让用户选择盘符完成文件处理操作?

问题修复方案

核心错误点(导致程序运行异常的原因)

  • 缺少必要头文件:代码没有引入stdio.h、ctype.h等依赖头文件,编译阶段就会出现未定义函数错误,无法正常生成可执行程序。
  • 字符串变量定义错误:char name = "tester"; 定义的是单字符变量,却赋值字符串常量,fprintf 用 %s 读取该变量时会触发非法内存访问,直接导致程序崩溃。
  • 缺少文件打开结果校验:第一次调用 fopen 后没有判断返回值,如果用户输入的盘符不存在、没有写入权限,fp 为NULL,后续fprintf写空指针也会触发崩溃。
  • 设备检测循环逻辑异常:循环内先打印提示再立刻执行system("cls"),用户完全看不到提示内容,且循环无休眠逻辑,会疯狂占用CPU资源。

修复后完整代码

#include <stdio.h>
#include <ctype.h>
#include <windows.h> // Windows平台专用,提供Sleep休眠函数

int main() {
    // 修正字符串变量定义
    char *name = "tester";
    int test_num = 5;
    char drivelet;
    
    printf("Enter drive letter: ");
    scanf(" %c", &drivelet);
    char temp = toupper(drivelet);
    // 新增盘符合法性校验
    if (temp < 'A' || temp > 'Z') {
        printf("Invalid drive letter input.\n");
        return 1;
    }

    char path[] = "?:\\uvuvuuv.txt";
    path[0] = temp;
    FILE *fp = fopen(path, "w+");
    // 新增文件打开结果校验
    if (fp == NULL) {
        printf("Failed to access drive %c:, please check if the USB drive is inserted properly.\n", temp);
        return 1;
    }
    fprintf(fp, "%s %d\n", name, test_num);
    fclose(fp);

    system("cls");
    char path1[] = "?:\\uvuvuuv.txt";
    path1[0] = temp;
    FILE *bio = fopen(path1, "r+");

    while (bio == NULL) {
        // 调整清屏和打印顺序,保证提示可见
        system("cls");
        printf("No card detected. Please insert card.");
        // 新增1秒休眠,降低CPU占用
        Sleep(1000);
        bio = fopen(path1, "r+");
    }
    system("cls");
    printf("Card detected!");
    fclose(bio);
    return 0;
}

额外优化说明

  • 新增盘符输入合法性校验,避免用户输入非字母内容导致路径异常
  • 替换了不规范的变量命名,提升代码可读性

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 06:39:00