views:

27

answers:

1

I hope I formatted the code correctly this time. Let me say first that the code works as is; it's in understanding some parts and modifying others that I run into trouble.

I'm going to delete my numerous comments and limit myself to a few questions on it. 1. Is FILE a keyword in Obj-C? What is its function? Why all caps? 2. What does "r" do? 3. The text file already has strings containing empty spaces, each ending with \n; why not make them NSStrings instead of c-strings? 4. Why, when I try to change the launch parameter of the file (using executables, clicking on arguments and plus, and typing in the parameter) to anything other than /tmp (such as /Desktop), do I get errors? After all, /tmp is a volatile, vulnerable place. This is the error I got for /Desktop: The Debugger has exited due to signal 10 (SIGBUS).

Here's the code:

#import <Foundation/Foundation.h>

int main (int argc, const char * argv[]) { NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

if (argc == 1)
{
    NSLog(@"You need to provide a file name");
    return 1;
}

FILE *wordFile = fopen(argv[1], "r");

char word[100]; 
while (fgets (word, 100, wordFile))
{
    word[strlen(word) - 1] = '\0';
    NSLog(@"%s is %d characs long", word, strlen(word));
}

fclose (wordFile);
[pool drain];
return 0;

}

A: 

Most of this is standard C stuff, it happens to be compiled as objective-c but FILE and fopen() and fgets() are plain old fashioned C.

FILE is presumbably a #define'd somewhere to refer to a structure definition. It is not a keyword, just a regular symbol defined (I think) in stdio.h.

"r" means "readable". Look up fopen for all the values that argument can have, but "r", "r+", "b", "a", "w" etc are some of the options.

Are you sure /Desktop is a valid directory? Change to that directory in a console window and type "pwd" to make sure youve got the right path. You might want to have an error message if wordFile is null (i.e. couldn't find the file or open it for some reason) before trying to use fgets on it.

rob
Doesn't "r" technically mean "open for read only"? And the others are "open for XXX only"?
MJB
Well I see it documented as "Open a file for reading. The file must exist." "r+" means read and write. But if it is only an r, yes, read only.
rob
Thanks for the help. Sorry about the delay getting back to you on this. But I did find everything you mentioned in a C std lib website.The error msg is there (NSLog "You need to ... file name").I'm not sure how to approach "change to that directory in a console window". Is that the same console window in Xcode that shows the program running? If so, what's the syntax I need to try to change directories? Is it cd /Desktop?
Rich