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
Iftest1.txtisn'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()returnsNULL. Callingfgetc(NULL)is exactly what triggers that memory access crash. str1is the wrong typefgetc()returns anint, not achar. This is becauseEOFis an integer value (usually-1), and if your system uses unsignedchar, comparing achartoEOFwill 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
相关产品推荐
相关产品推荐

