C Programming Functions, File I/O ME 325 Spring, 2007
Overview Multidimensional Array Functions File I/O
Multidimensional arrays • Multidimensional arrays are arrays that have more than one index. • Multidimensional arrays can be thought of as having values that spread across two or more dimensions.
Declaration • The syntax used to actually declare a two dimensional array is almost the same as that used for declaring a onedimensional array, except that you include a set of brackets for each dimension, and include the size of the dimension. For example, here is an array that is large enough to hold a standard checkers board, with 8 rows and 8 columns, (64 elements): – int a[8][8]; • a[1][2] is element 11 of the array.
Multi. arrays, example #include <stdio.h> enum {nRows=8, nCols=8}; /* Define number of columns and rows */ int main() { int row, col; int array[nRows][nCols]; /* Declares an array like a chessboard */ for ( row = 0 ; row < nRows ; row++ ) { for ( col = 0; col < nCols; cols++ ) array[row][col] = row * col; /* Set each element to a value */ } printf("\t"); for ( col = 0 ; col < nCols ; col++ ) printf("%d\t",col); printf("\n\n" ); for ( row = 0 ; row < nRows ; row++ ) { printf("%d:",row); for ( col = 0 ; col < nCols ; col++ ) printf("\t%d",array[row][col] ); printf( "\n" ); } getchar(); return 0; }
Example output • Top row is the column index, • First column is the row index • The body is the value of array[row][col] – array[2][3]=6
Functions • Functions are blocks of code that perform a number of pre-defined commands to accomplish something productive. • You can either use the built-in library functions or you can create your own functions. • Functions generally require a prototype return-type function_name ( arg_type arg1, ..., arg_type argN ); arg_type just means the type for each argument -- for instance, an int, a float, or a char
Function, Example #include <stdio.h> #include <stdlib.h> /*Function prototype, return int and takes two int args, x and y */ int mult ( int x, int y ); int main() { int x,y; printf( "Please input two numbers to be multiplied, x y : " ); scanf( "%d %d", &x, &y ); printf( "The product of %d x %d = %d\n", x, y, mult( x, y ) ); system(“pause”); return 0; } /*Function return int and takes two int args, x and y */ int mult (int x, int y) { return (x * y); }
File I/O • For C File I/O you need to use a FILE pointer, which will let the program keep track of the file being accessed FILE *fp;
/* * indicate a pointer */
• To open a file you need to use the fopen function, which returns a FILE pointer FILE *fopen(const char *filename, const char *mode); The first argument is the file name we are accessing The second args is the mode determine that type of access to the file among other features.
fopen modes • r - open for reading • w - open for writing (file need not exist) • a - open for appending (file need not exist) • r+ - open for reading and writing, start at beginning • w+ - open for reading and writing (overwrite file) • a+ - open for reading and writing
fopen, how FILE *fp=NULL; /* NULL ? */ fp=fopen( “c:\\output.txt” , ”w+” ); /* \\? *\ if(fp != NULL) /* Check the file pointer */ { perform file output functions .. fclose( fp ); /* Close file and flush data */
fopen fopen is used to open a file for read, write or update
• Prototype: FILE *fopen(const char *filename, const char *mode);
• Syntax: FILE *fp; fp = fopen( “c:\\file1.dat", "r");
• Notes: – filename - is the name of the file. – mode - r - read file. - w - Write to file.
fclose fclose is used to close a file.
• Prototype: int fclose( FILE *stream);
• Syntax: FILE *fp; fclose(fp);
feof • feof is used to check for end of file condition Prototype int feof(File *fp); return non zero if not end of file
Syntax File *fp; while( !feof(fp) ) { do file I/O if( feof(fp) ) break;l }
fprintf fprintf is used to write formated data and a file. It is basically a printf and so uses the same escape sequences and format identifers
Prototype fprintf(File *fp , const char *format , …);
Syntax File *fp; fprintf(fp,”This is line1\nThis is line2”); fclose(fp):
fscanf The fscanf() function reads from the named file pointer, it is similar to scanf which read from the standard input. Prototype int fscanf(FILE *stream, const char *format, ... );
Syntax File *fp; int x1; fscanf(fp,“%d”,&x1);
fputs • fputs is used to write string to stream Prototypes int fputs(const char *s, FILE *stream); Syntax File *fp; fputs(“x y”,fp);
fgets fgets is used to read a line from a file. Prototype: char *fgets(char *s, int n, FILE *stream);
Syntax: char read_line[80]; char *return_code; FILE *file_pointer; return_code=fgets( read_line, 80, file_pointer); return_code == NULL when an error occours. The EOF is considered to be an ERROR!
Pointers • A pointer is a variable which contains the address in memory of another variable. We can have a pointer to any variable type. • The operator & gives the “address of a variable''. • The indirection or dereference operator * gives the “contents of an object pointed to by a pointer''. • To declare a pointer to a variable do:
Pointers and Memory
Pointers, Example #include <stdio.h> int main() { int x=1,y=2; int *ip; /* ip is a pointer to and address in memory*/ /* Print the value of x and address of x (), y and address of y */ /* Print the value in the address space of ip *ip, and the address of ip */ printf("x=%d (%d)\ty=%d (%d)\n",x,&x,y,&y); printf("*ip=%d ip=(%d)\n",*ip,ip); printf("-------------------------------------\n\n"); /* assign the address of x to ip, therefore *ip and x have the same value */ ip=&x; printf("Setting ip=&x\n"); printf("x=%d (%d)\ty=%d (%d)\n",x,&x,y,&y); printf("*ip=%d ip=(%d)\n",*ip,ip); printf("-------------------------------------\n");
Pointers, Example cont… /* assign the value of *ip to y, x and y would have the same value */ y=*ip; printf("Setting y=*ip\n"); printf("x=%d (%d)\ty=%d (%d)\n",x,&x,y,&y); printf("*ip=%d ip=(%d)\n",*ip,ip); printf("-------------------------------------\n"); /* assign a value of 5 top *ip since x and ip point to the same address*/ /* then x would have the same value*/ *ip=5; printf("Setting *ip=5\n"); printf("x=%d (%d)\ty=%d (%d)\n",x,&x,y,&y); printf("*ip=%d ip=(%d)\n",*ip,ip); printf("-------------------------------------\n"); getchar(); return 0; }
Pointers Example Output
Pointer and Functions • When C passes arguments to functions it passes them by value. • There are many cases when we may want to alter a passed argument in the function and receive the new value back once to function has finished. To do that we use pointers as arguments. • To declare a function with pointers arguments – retrun_type func(arg_type *arg1,arg_type *arg2); – To call this function we need to pass the address of arguments not their values
Function and Pointers Example
#include <stdio.h> void swap(int *px, int *py) { int temp; temp = *px; /* copy contents of pointer px to temp */ *px = *py; /* copy content pv to content of pointer px */ *py = temp; /* copy the saved content of px to pv */ } int main() { int a=5,b=7; printf(“a=%d \t b=%d\n” , a , b); /* Call the swap function */ swap(&a , &b); printf(“after swap a=%d \t b=%d\n”,a,b); getch(); return 0; }
Pointers and Arrays • Pointers and arrays are very closely linked in C. • Think of array elements arranged in consecutive memory locations int a[10] , x; int *pa; pa = &a[0]; x = *pa; x = *(pa+1); x = *(pa+i);
/* /* /* /*
pa pointer to address of a[0] */ x = contents of pa (a[0] in this case) */ x = content of a[1] */ x = content of a[i] */
Pointers and Arrays • C however is much more subtle in its link between arrays and pointers. pa = a; is equivalent to pa = &a[0]; and pa[i] = *(pa + i) = a[i];
Array Pointers Example #include <stdio.h> #define ARRAY_SIZE 10 /* Functions Protottypes */ void DisplayArray( int array[] ); void InitArray( int array[] ); void MultArray( int array[] , int scalar ); int main() { int a[ARRAY_SIZE]; printf(“\n ** Initialize and display Array **\n”); InitArray(a); DisplayArray(a); printf(“\n ** Multiply array by 2 and display Array **\n”); MultArray(a,2); DisplayArray(a); getchar(); return 0; }
Array Pointers Example, Cont… void DisplayArray( int array[] ) { for(int i=0 ; i