Im using xcode 4.6 and im having problems reading files using the fopen function in c

Im using xcode 4.6 and im having problems reading files using the fopen function in c 😢

MacBook Pro (13-inch, Mid 2012), OS X Mountain Lion (10.8.2)

Posted on Mar 1, 2013 3:03 PM

Reply
7 replies

Mar 2, 2013 12:33 AM in response to Frank Caggiano

So for example web web I run running a code such as


FILE *fp;

Fp=fopen("hello_world.txt","r");


It always gives me the message "build failed"


Just to clear a couple of things ,the txt file is located in the same directory as main.c

And I use fclose at the end of the program.

I've tried running the code on terminal and different IDE's such as eclipse and its working perfectly .

Mar 2, 2013 5:23 AM in response to Gizmo95

Just to clear a couple of things ,the txt file is located in the same directory as main.c


That is most likely your problem. The location of the source files is not the same as the location of the compled code. Xcode places the compiled code in a different directory from the source.


It is always a good idea to either use the absolute path for files your program will open or to use a relative path you can construct in your program. For example putting the file in your home directory or some other well know place.

Mar 2, 2013 7:11 AM in response to Keith Barkley

Yes, but that would not cause the "build failed" message.


right I missed that part. Looks like two problems then.


//

// main.m

// ASCTestFopen

//

// Created by Frank Caggiano on 3/2/13.

// Copyright (c) 2013 Frank Caggiano. All rights reserved.

//


#import <Foundation/Foundation.h>

#include <stdio.h>


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

{


@autoreleasepool {

FILE *fp, *fopen();

// insert code here...

if((fp = fopen("~/test.txt","r")) == NULL)

NSLog(@"open failed");

}

return0;

}

This will compile ad run in Xcode with a project type of comand line tool

Mar 4, 2013 8:34 AM in response to Gizmo95

So for example web web I run running a code such as


FILE *fp;

Fp=fopen("hello_world.txt","r");


It always gives me the message "build failed"



Try File *fp = fopen("hello_world.txt","r");


if((fp = fopen("~/test.txt","r")) == NULL)


fopen doesn't understand ~ (twidle) - that is a shell feature for the users home directory and will not get translated by the fopen call.

This thread has been closed by the system or the community team. You may vote for any posts you find helpful, or search the Community for additional answers.

Im using xcode 4.6 and im having problems reading files using the fopen function in c

Welcome to Apple Support Community
A forum where Apple customers help each other with their products. Get started with your Apple Account.