A.6. Chapter 6

A.6.1. Exercise 1 solution

  1. Open the Grepper project in Xcode, and make the highlighted changes in the following code to the main.c file:

    #include <stdio.h>
    #include <string.h>
    
    // Global constants
    const int MAX_STRING_LENGTH = 256;
    
    // Main function
    int main (int argc, const char * argv[]) {
    
        // Get string to search for, which is the last argument
        const char *searchString = argv[argc-1];
    
        // Loop over files
        unsigned int fileIndex;
        for ( fileIndex = 1; fileIndex < argc-1; ++fileIndex ) {
            // Get input file path from standard input
            const char *inpPath = argv[fileIndex];
    
            // Open file
            FILE *inpFile;
    inpFile = fopen(inpPath, "r");
    
            // Loop over lines in the input file, until there
            // are none left
            char line[MAX_STRING_LENGTH];
            int lineCount = 0;
            while ( fgets(line, MAX_STRING_LENGTH-1, inpFile) ) {
                ++lineCount;
                if ( strstr(line, searchString) ) {
                    printf("In file %s, line %d:\t%s", inpPath, lineCount, line);
                }
            }
    
            // Close files
            fclose(inpFile);
    
        } // End loop over files
    
        return 0;
    }
  2. Select the Grepper executable in the Executables group of the Groups & Files panel on the left of the project window. Choose Get Info from the File menu and select the Arguments tab in the Info window that appears. Using the + button, add arguments to the Arguments table at the top. Add the paths of two or more text files first, and a string to search for as the last argument.

  3. Compile and run the program by clicking the Build and Go toolbar item in the main project window.

  4. Verify from the results that ...

Get Beginning Mac OS® X Programming now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.