Reading a file from Terminal (obj-c)

Discussion in 'Programming & Software Development' started by bwen, Mar 26, 2009.

  1. bwen

    bwen Member

    Feb 5, 2008
    I need to make a little program that reads a file name from command line which then opens a textfile and then read what's in the textfile before printing the contents back into the terminal window. I've done the program in C, I'm just extremely new with objective-c

    #include <stdio.h>
    #include <stdlib.h>
    int main(int argc, char * argv[]) {
    	FILE *file;
    	char c[300];	
    	int n;
    	char * filename = argv[1];
    	file = fopen(filename, "r");
    	if(file==NULL) {		                 // check if it is possible to open the filename
    		printf("Error: can't open file.\n");
    		return 1;
    	} else {
    		printf("\nFile opened successfully.\n");
    		n = fread(c, 1, sizeof(c), file);	// passing a char array, reading size of given array and 
    							// passing it through the appropiate number of times
    		c[n] = '\0';				// a char array is only a string if it has 
    							// the null character at the end 
    		printf("%s\n", c);			// print out the string
    		printf("Characters read: %d\n\n", n);	// just print the amount of characters passed 
    		fclose(file);				// to close the file
    		return 0;
    Any help would be greatly appreciated.
  2. Dedge

    Dedge Member

    Dec 23, 2001
    Brisbane, QLD
    NSString has a convenience method for reading the contents of a file in to a string.

    NSString *str = [NSString stringWithContentsOfFile: @"/path/to/file"];
    NSLog(@"%@", str);
    NSLog is Objective-C's printf (Except it also prints a timestamp). In addition to C place holders, %@ is for NSString.

    Path MUST be a of type NSString. If you're passing parameters from C's argv, you'll need to cast them to NSString. Fortunately, there's a convenience method for that too.

    NSString *path = [NSString stringWithCString: argv[1]];

Share This Page