如何在 Xcode 中用 C 语言执行文件 I/O?
我使用 Xcode 作为 C 的 IDE。
#include <stdio.h>
int main (int argc, const char * argv[])
{
FILE *file;
int numberTest = 0;
file = fopen("fileTest.dat", "r");
if (file == NULL)
{
printf("File not found!\n");
}
fscanf(file, "%d", &numberTest);
printf("I read the number: %d\n", numberTest);
fclose(file);
return 0;
}
该文件位于我的 Xcode 包中,并且与 HDD 中项目的其余部分位于同一文件夹中。问题是 fopen() 不断返回 NULL。
I am using Xcode as my IDE for C.
#include <stdio.h>
int main (int argc, const char * argv[])
{
FILE *file;
int numberTest = 0;
file = fopen("fileTest.dat", "r");
if (file == NULL)
{
printf("File not found!\n");
}
fscanf(file, "%d", &numberTest);
printf("I read the number: %d\n", numberTest);
fclose(file);
return 0;
}
The file is in my Xcode bundle and is in the same folder as the rest of the project in the HDD. The problem is that fopen() keeps returning NULL.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您假设启动可执行文件时该文件位于当前工作目录中,但事实可能并非如此,而且这始终是一个错误的假设,即使在某些情况下碰巧是这样。
作为快速修复,您现在可以硬编码文件的绝对路径,例如
You're assuming that the file is in the current working directory when the executable is launched, which it probably isn't, and which is always a bad assumption anyway, even if it happens to be true in some cases.
As a quick fix you can just hard code the absolute path to the file for now, e.g.
找不到该文件,因为运行可执行文件时它不在您的路径上。您需要将该文件添加到您的目标,以便在构建源代码时将其复制到构建目录。
The file is not found because it is not on your path when the executable is run. You will need to add the file to your target so that it is copied to the build directory when you build your sources.