kabrice
kabrice

Reputation: 1625

C - Can't create new .txt file from Xcode

I just began to work in C programming with Xcode. But I have a problem now. I wrote this code :

#include <stdio.h>
#include <stdlib.h>

int main(int argc, const char * argv[]) {

    FILE *fp;

    fp = fopen("toto.txt", "w+");
    fputs("hi", fp);

    fclose(fp);

    return 0;
}

As toto.txt doesn't exist, it's supposed to create and open it, but nothing happens, I don't know why.

Upvotes: 2

Views: 5924

Answers (2)

Stefan
Stefan

Reputation: 73

I think your problem is with Xcode current working directory settings. You need to update the project's current Scheme.

  1. Stop running your application.
  2. Go to Product -> Scheme -> Edit Scheme.

  1. Select Run from Left panel -> Options and check Working Directory - use custom working directory.

Now your C project will know where should write output files.

Upvotes: 7

Tapani
Tapani

Reputation: 3231

Check the return value of fopen. It is possible that creating the file fails. The reason may be some permissions. You should check what is the current directory where the file should be written or add a full path to the filename.

int main(int argc, const char * argv[])
{
  FILE *fp;
  fp = fopen("/mydir/toto.txt", "w+");
  if (fp != NULL)
  {
    fputs("hi", fp);
    fclose(fp);
  }
  else {
    printf("Failed to create the file.\n")
  }
  return 0;
}

Upvotes: 2

Related Questions