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

C语言读取多行文本文件时遇EXC_BAD_ACCESS错误求助

解决C语言读取文件时EXC_BAD_ACCESS错误的问题

Hey Danwoo, let's figure out why you're hitting that EXC_BAD_ACCESS error in Xcode—this is almost certainly a code issue, not an environment problem. Let's break it down:

First, what does that error mean?

EXC_BAD_ACCESS(code=1, address=0x68) tells you your program is trying to access memory it shouldn't. In your case, this happens because you're calling fgetc() on an invalid file pointer.

The problems in your code:

  • You never check if the file opened successfully
    If test1.txt isn't in the right location (Xcode runs programs from a specific build directory, not where your source file is) or the file doesn't exist, fopen() returns NULL. Calling fgetc(NULL) is exactly what triggers that memory access crash.
  • str1 is the wrong type
    fgetc() returns an int, not a char. This is because EOF is an integer value (usually -1), and if your system uses unsigned char, comparing a char to EOF will never be true—leading to an infinite loop once you fix the first issue.

Fixed code:

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

int main(){ 
    FILE *fptr; 
    int str1; // 改为int类型,正确处理EOF
    
    // 打开文件并检查是否成功
    fptr = fopen("test1.txt", "r");
    if (fptr == NULL) {
        printf("Error: 无法打开文件!\n");
        return 1; // 带错误码退出
    }

    printf("\n The content of the file is :\n"); 
    str1 = fgetc(fptr); 
    while (str1 != EOF) { 
        printf("%c", str1); 
        str1 = fgetc(fptr); 
    } 
    printf("\n\n"); 
    fclose(fptr); 
    return 0; 
}

Quick tips for Xcode:

To make sure your test1.txt is accessible:

  • 右键项目导航栏中的项目 > 选择"Add Files to [你的项目名]" > 选中你的文本文件
  • 在添加对话框中,确保勾选"Copy items if needed"和"Add to targets",这样文件会被复制到程序运行的构建目录中。

这样修改后就能解决崩溃问题,正常读取文件内容了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 07:11:54