Error when working with fopen()

Discussion in 'Mac Programming' started by sheepopo39, Jan 9, 2010.

  1. sheepopo39 macrumors 6502

    Joined:
    Sep 18, 2008
    #1
    I was reading through Learn C on the Mac and I got up to a point which is dealing with files and I was looking through the first source code example, and when I run the example, it me one of the custom errors that the author put in, instead of reading the file. I am really stumped as to what is causing this, also, from what I've checked all of the other examples in the chapter (deals with files) report some form of error, in which it can't find the file. I was wondering if anyone could find as to what is wrong. I uploaded the project file if anyone wanted to take a look at it, along with main.c below.

    Thanks,

    John

    Code:

    Code:
    #include <stdio.h>
    
    int main (int argc, const char * argv[]) {
    	FILE	*fp;
    	int	c;
    	
    	fp = fopen( "../../My Data File", "r" );
    	
    	if ( NULL == fp ) {
            printf( "Error opening ../My Data File" );
        } else {
    		while ( (c = fgetc( fp )) != EOF )
    			putchar( c );
    		
    		fclose( fp );
    	}
    	
    	return 0;
    }
     

    Attached Files:

  2. Matthew Yohe macrumors 68020

    Joined:
    Oct 12, 2006
    #2
    Works here.

    But are you running it inside XCode? or rather, inside the Build/Debug folder that XCode creates?

    See, this code makes the assumption that you dump the contents of that zip file in a single directory and then run it with XCode. That's why it has the"../../My Data File"

    Because that application "printFile" basically saying, "I'm being run from /build/Debug/ , and I need access to a file that is not in Debug, not in build, but in the directory above build. So, ../../My Data File"
     
  3. sheepopo39 thread starter macrumors 6502

    Joined:
    Sep 18, 2008
    #3
    Odd, I tried it on two seperate computers (one running xcode 3.2, the other 3.1) and neither worked.

    Hmmm.
     
  4. chown33 macrumors 604

    Joined:
    Aug 9, 2009
    #4
    In order to debug this, you first need to understand what a working directory and a relative path are:
    http://en.wikipedia.org/wiki/Working_directory
    http://en.wikipedia.org/wiki/Relative_path


    You should also look at the C function getcwd():
    http://developer.apple.com/mac/library/documentation/Darwin/Reference/ManPages/man3/getcwd.3.html

    For example, call the function and print the resulting string in your program. Then figure out where your relative pathname points relative to that working directory. If the printed directory isn't what you expected, then figure out why not, or post the exact procedure you're using to run the program.
     

Share This Page