Thread: Simple code compiles in windows, does not in xCode.

  1. #1
    Registered User
    Join Date
    Jan 2012
    Posts
    4

    Simple code compiles in windows, does not in xCode.

    Hi all,

    I'm in the early stages of learning C, and I want to develop on OSX. I wrote a simple program that uses fopen() on a .txt file (in the local directory of the source.c file) and uses fscanf() to read the first line into an integer.

    It works fine using codeblocks in a windows environment, but it doesn't work on any ide I've tried on OSX. It returns "Segmentation Fault: 11". What am I missing?

    Code:
    #include <stdio.h>
    
    int main ()
    {
        int num = 0;
        FILE *fpointer;
        fpointer = fopen("test.txt", "r");
        fscanf(fpointer, "%d", &num);
        printf("%d\n", num);
        
        return 0;
    }

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    You're missing a
    if ( fpointer == NULL )
    to check to see if you opened the file successfully (or not).
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    Registered User
    Join Date
    Jan 2012
    Posts
    4
    Quote Originally Posted by Salem View Post
    You're missing a
    if ( fpointer == NULL )
    to check to see if you opened the file successfully (or not).
    Gotcha, fopen definitely isn't populating that pointer. But why wouldn't it? test.txt is in the local directory of the source.c.... does OSX not work that way?

  4. #4
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    It matters if it is where the executable is, not where the source is (since you aren't specifying the full path). It's either not where it expects it to be, or you don't have permissions to access it.


    Quzah.
    Hope is the first step on the road to disappointment.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. exc_bad_access error when compiling c code in xcode
    By new_cuser in forum C Programming
    Replies: 6
    Last Post: 07-27-2011, 03:43 PM
  2. C Code in Xcode
    By rmcinnes in forum C Programming
    Replies: 2
    Last Post: 04-11-2011, 07:27 AM
  3. Replies: 6
    Last Post: 03-09-2011, 06:38 AM
  4. Why does Dev-C++ never compiles code for me?
    By Mung_Foo in forum C++ Programming
    Replies: 11
    Last Post: 08-14-2003, 10:16 PM
  5. Simple Program wont execute after compiles w. no errors
    By Unregistered in forum Windows Programming
    Replies: 1
    Last Post: 02-03-2002, 04:24 PM