-2

I was trying to figure out how to open a text file inside C.

So far I've been using Peoplia (app that actually compiles code for me) and working with files was as simple as opening and closing them.

The way I usually did it was this:

int main()
{
  FILE *fr;
  fr = fopen("file.txt","r");

  // loop to go through the file and do some stuff

  return 0;
}

I'm using the newest version of Xcode, which I believe is 6.1 and all the guides to adding file to the project were outdated.

So how do I work with a file in Xcode, anyone?

Paul R
  • 208,748
  • 37
  • 389
  • 560
IamLee
  • 5
  • 1
  • 5

1 Answers1

0

It's the same as with any other OS and C compiler, but be aware that you should not make any assumptions about the working directory - use full paths or set the working directory yourself.

So either:

#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;
}

or:

#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;
}
Paul R
  • 208,748
  • 37
  • 389
  • 560
  • Using `chdir()` is a terrible thing to suggest. – trojanfoe Nov 10 '14 at 15:22
  • @trojanfoe: really ? why ? – Paul R Nov 10 '14 at 15:22
  • Because it complicates things. Firstly it's unexpected and very few command line tools do change directory and simple things like writing output into a file in the current directory mean that you need to 1) remember your original CWD and 2) generate the fullpath back into that CWD. It's not necessary in almost all cases. – trojanfoe Nov 10 '14 at 15:25
  • What you say is true for command line tools in general, but when running a command line tool from within Xcode the working directory is typically `/`, so you either need to set it to something else in the scheme, or change it from within the code, neither of which is ideal, but it might be more practical than having to use absolute paths. – Paul R Nov 10 '14 at 15:27