CITS2002 Systems Programming  
prev
next CITS2002 CITS2002 schedule  

The main() function

All of our C source files now include our local header file. Remembering that file inclusion simply "pulls in" the textual content of the file, our C files are now provided with the declarations of all global functions and global variables.

Thus, our code may now call global functions, and access global variables, without (again) declaring their existence:


#include  "calcmarks.h"    // local header file provides declarations

int main(int argc, char *argv[])
{
    int nmarks = 0;

//  IF WE RECEIVED NO COMMAND-LINE ARGUMENTS, READ THE MARKS FROM stdin
    if(argc == 1) {
         nmarks += readmarks(stdin);
    }
//  OTHERWISE WE ASSUME THAT EACH COMMAND-LINE ARGUMENT IS A FILE NAME
    else {
        for(int a=1 ; a<argc ; ++a) {
            FILE *fp = fopen(argv[a], "r");

            if(fp == NULL) {
                printf("Cannot open %s\n", argv[a]);  
                exit(EXIT_FAILURE);
            }
            nmarks += readmarks(fp);
//  CLOSE THE FILE THAT WE OPENED
            fclose(fp);
        }
    }
//  IF WE RECEIVED SOME MARKS, REPORT THEIR CORRELATION
    if(nmarks > 0) {
        correlation(nmarks);
    }
    return 0;
}

In the above function, we have used to a local variable, nmarks, to maintain a value (both receiving it from function calls, and passing it to other functions).

nmarks could have been another global variable but, generally, we strive to minimize the number of globals.

 


CITS2002 Systems Programming, Lecture 17, p7, 26th September 2023.