2

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.

8
  • 4
    Did you check that fopen returns a valid file handle? it may fail to create the file to the current directory. Commented Feb 22, 2016 at 10:27
  • 2
    Are you certain that you're looking for the file in the right place? If you're running inside XCode, the default working directory is in your build folder, not in the source folder. Commented Feb 22, 2016 at 10:32
  • 1
    This may be a permission issue, for instance. Are you sure you are allowed to create files in this directory? Commented Feb 22, 2016 at 10:33
  • @Almeida is not a permission issue, I've all the rights inside my directories. Commented Feb 22, 2016 at 10:42
  • 1
    if (NULL == fp) { // failed } Commented Feb 22, 2016 at 10:43

2 Answers 2

7

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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

1 Comment

I've just change your code a little bit according to my file and my directories : Console message : "Failed to create the file." int main(int argc, const char * argv[]) { FILE * fp; fp = fopen("/Fichiers/toto.txt", "w+"); if (fp != NULL) { fputs("hi", fp); fclose(fp); } else { printf("Failed to create the file.\n"); } return 0; } but it doesn't still work, I don't know why ! While I've changed the permission using this method : osxdaily.com/2011/02/21/change-file-permissions-mac

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.