使用Xcode IDE在C中打开文本文件



我试图弄清楚如何在C.中打开一个文本文件

到目前为止,我一直在使用Peopleia(实际上是为我编译代码的应用程序),处理文件就像打开和关闭它们一样简单。

我通常这样做:

int main()
{
  FILE *fr;
  fr = fopen("file.txt","r");
  // loop to go through the file and do some stuff
  return 0;
}

我使用的是最新版本的Xcode,我相信它是6.1,所有向项目添加文件的指南都已经过时了。

那么我该如何使用Xcode中的文件呢?

它与任何其他操作系统和C编译器相同,但请注意,您不应该对工作目录做出任何假设-使用完整路径或自己设置工作目录。

所以要么:

#include <stdio.h>
int main()
{
    FILE *f = fopen("/Users/shortname/foo.txt", "r"); // open file using absolute path
    if (f != NULL)
    {
        // do stuff
        fclose(f);
    }
    return 0;
}

或:

#include <stdio.h>
#include <unistd.h>
int main()
{
    FILE *f = NULL;
    chdir("/Users/shortname");  // set working directory
    f = fopen("foo.txt", "r");  // open file using relative path
    if (f != NULL)
    {
        // do stuff
        fclose(f);
    }
    return 0;
}

最新更新