gpt4 book ai didi

c - 如何在 Xcode 中用 C 执行文件 I/O?

转载 作者:行者123 更新时间:2023-12-04 10:14:14 26 4
gpt4 key购买 nike

我使用 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");

关于c - 如何在 Xcode 中用 C 执行文件 I/O?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7418601/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com