[英]How to perform file I/O in C in Xcode?
我使用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。
你假设在启动可执行文件时文件位于当前工作目录中,它可能不是,并且无论如何总是一个坏的假设,即使它在某些情况下恰好是真的。
作为快速修复,您现在可以硬编码文件的绝对路径,例如
file = fopen("/Users/me/Desktop/fileTest.dat", "r");
找不到该文件,因为在运行可执行文件时它不在您的路径上。 您需要将文件添加到目标,以便在构建源时将其复制到构建目录。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.