90 likes | 155 Views
Hands on with Functions and IO. Program Inputs. How do you pass information into your program? Use arguments in main() int main(int argc, char * argv[]) The names argc and argv are usually used for the parameters, but a programmer could use different names. Program Inputs.
E N D
Program Inputs • How do you pass information into your program? • Use arguments in main() int main(int argc, char * argv[]) • The names argc and argv are usually used for the parameters, but a programmer could use different names. 2
Program Inputs • The command words can be accessed as argv[0] through argv[argc - 1]. • The program name is the first word on the command line, which is argv[0]. • The command-line arguments are argv[1] through argv[argc - 1]. • argc holds how many arguments are passed 3
Simple Example #include <stdio.h> int main(int argc, char * argv[]) { int i; printf ("You entered %d words\n",argc); for (i = 1; i < argc; i++) printf("%s ", argv[i]); printf("\n"); } Now lets use it 4
File IO review • We have discussed fopen, fclose, fprintf, & fscanf • Example: • Look at the file_io.c example 5
More File IO • To do more interesting things, need to more fine toothed control… • fgetc() – Reads one character from a file • fputc() – Writes one character from a file • Example: my_cat.c 6
Basic Database • Get the file “database.txt” from the class website in the Handouts and Links section • Write a simple function that will read the elements out of the database and add them to a linked list that you dynamically create • You will need to make a structure to hold them • You will need a function to add a node to the linked list • Now write 2 functions, one to add a node, one to delete, the add should prompt the user for the fields, the delete should ask for the ID or name • Write a final function that will save the database back to the file
Caesar Cipher Algorithm Caesar's code or Caesar shift, is one of the simplest and most widely known encryption techniques. It is a type of substitution cipher in which each letter in the plaintext is replaced by a letter some fixed number of positions down the alphabet. 8
Activity Part 1: • Write two functions, one called Caesar_Encrypt() the other called Caesar_Decrypt(). • The Caesar_Encrypt should take 2 inputs, a string of characters and a key. The function should shift the characters by the key and account for “roll-around” at the end of the alphabet. • The Caesar_Decrypt() should take the same types of input as the Caesar_Encrypt() function but reverse the process. • Test the above with some character arrays. • Put the functions in a file called crypto.c and make a header called crypto.h • Now uses these to read in a file of text and produce a new file with the extension “.enc” Part 2: 9