user2044189
user2044189

Reputation: 87

fscanf not reading in a file in Xcode in C

I'm trying to get my xcode to read in a file, but I keep getting a "build succeeded" and then (11db) as the output.

I have saved a file called "sudokode.in" to my desktop, and that's what I'm trying to open.

The file only has an integer, 19, in it.

I just want to print out 19 to the screen.

I have never gotten my Xcode to read a file before, so I wouldn't know if I have to set it up, or what. I have searched online and haven't found a real solution to this problem.

I appreciate the help.

int main() {

int num;

FILE* ifp = fopen("sudokode.in", "r");
fscanf(ifp, "%d", &num);

printf("%d", num);

return 0;
}

Upvotes: 1

Views: 2182

Answers (2)

MuleskinnerRR
MuleskinnerRR

Reputation: 1

To set up your Working Directory to read and write to files in Xcode, go to Product --> Scheme --> Edit Scheme, and click that.

Then, click the check box by "Working Directory" and use the little gray file icon at the end of the field below to set the working directory.

I found a great explanation of how to do this for basic command-line projects in c on Xcode here:

https://www.meandmark.com/blog/2013/12/setting-the-current-working-directory-for-xcode-command-line-projects/

Upvotes: 0

ryyst
ryyst

Reputation: 9801

The file probably doesn't exist. If that's the case, ifp will be NULL, so check for that:

int main() {

int num;

FILE* ifp = fopen("sudokode.in", "r");
if (ifp == NULL) {
    printf("Oops, this file doesn't exist!\n");
    return -1;
}
fscanf(ifp, "%d", &num);

printf("%d", num);

return 0;
}

Your program only works when you run it from the same directory that sudoke.in is stored in. You can use absolute paths (such as /User/John/Desktop/sudoke.in) instead.

Upvotes: 4

Related Questions