tags:

views:

175

answers:

1

I am trying to open a text file with C++ in Mac OS X but I always get a Bus error.

I do not care where to put the file. I just need to read it. Am I writing its address wrong? or that Bus Error has another reason?

FILE *dic;
dic = fopen("DICT","rb");

dic = fopen("./DICT","rb");

dic = fopen("~/DICT","rb");

dic = fopen("~//DICT","rb");
+3  A: 

With a little bit of clarification I see the problem in your C code (not C++!) is that fopen() returns NULL. You can check what the problem really is by reporting the detailed error:

if( (dic = fopen("DICT", "rb") == NULL ) {
    fprintf(stderr, "%s\n", perror("ERROR:"));
    exit(1);
}

If fopen() fails to find the file on the user's desktop and you wish your code to work on multiple platforms then you might define a function to get the user's desktop directory for using with fopen(). Something like

char* user_desktop(char* buf, size_t len)
{
    const char* const DESKTOP_DIR = 
#ifdef PC
    "C:\\Documents and Settings\\Pooya\\Desktop\\"
#elif defined(OSX)
    "/Users/Pooya/Desktop/"
#elif defined(LINUX)
    "/home/users/pooya/Desktop/"
// fail to compile if no OS specified ...
#endif
    return strncpy(buf, DESKTOP_DIR, len);
}

You probably want to look into a more robust way of getting the path of the desktop for each operating system. Most operating systems have an API for this, so do your research. There are also more robust ways of splitting behaviour for various platforms, you can look into that or open a different question about that. I just wanted to express my idea, of having a function which will return you the appropriate desktop path no matter on which platform you compile your code.

wilhelmtell
Hard-coding paths is no portable solution.
Georg Fritzsche
Yes, I just want to give a clear idea of what I mean. Most operating systems have API for getting this sort of paths, but putting that in code here would distract from my point.
wilhelmtell
Something was wrong about the file. I have saved it again and it works right now.
Pooya