tags:

views:

119

answers:

3

hello. i tried to read text file in xcode but this "EXC_BAD_ACCESS message showed up when i tried to build my program

here is my code and i put inputA.txt file in the same folder with project file my friend told me that i should put txt file in debug folder is this why i cannot read txt file in this code? please help me...

macbook user.

int main (int argc, const char * argv[]) {
    FILE* fp;  
    char mychar;  
    char arr[50][2] = {0, };  
    int i = 0;  
    int j, k;  
    graphType* G_;  
    G_ = (graphType*)malloc(sizeof(graphType));  
    Create(G_); 
    fp = fopen("inputA.txt", "r");
    //fp = fopen("inputB.txt", "r");
    //fp = fopen("inputC.txt", "r");

    while(1){
        for(j = 0 ; j < 2 ; j++){
            mychar = fgetc(fp);
            if(mychar == EOF)
                break;
            else if(mychar == ' ')
                continue;
            arr[i][j] = mychar;
        }
        i++;
    }
A: 

Most likely inputA.txt is not in the same file as the binary. You should make sure the text file is copied to the output directory in your project (whether manually or by hand).

Also, fopen will return NULL if the file couldn't be opened, so you might want to add a check for that.

if (fp == NULL)
{
    printf("Could not open file!");
    return 1;
}
Mark Rushakoff
A: 

Per default your binary will be generated in ProjectDir/build/Mode, with Mode being Debug or Release, and will have that as its working directory. If you want to refer to a file in the project directory, you'd have to use ../../input.txt in that case.

The build locations are configured in the "Build Locations" section in a targets or projects build tab. The working directory can be manually changed in the settings for the executable ("General", "Set the working directory to:") if needed.

If you are having doubts then you can always find out what the working directory is:

#include <unistd.h>
int main() {
    char buf[2048];
    getcwd(buf, sizeof(buf));
    printf("%s", buf);
}
Georg Fritzsche
A: 

fopen is probably returning null because your text file isn't in the right place. Don't forget to check for null!

Ken Aspeslagh