Exercise 5 (SS 2016) 28.06.2016 What will I learn in the 5. exercise Strings (and a little bit about pointer) String functions in strings.h Files Exercise(s) 1
Home exercise 4 (3 points) Write a program which is able to handle students exam results. The data for an exam are: - Mark: 0.7-5.0 - Exam identifier : simple number 6 digits - Matriculation-No.: simple number 6 digits Requirements: The program asks for the number of students. The program reserves memory via malloc in dependency of the number of students. The program aks for all students all data (Mark, Exam-ID, Matr). The program determines the number of passed (Mark <= 4.0) results. Strings C does not have an own String datatype Implemented as array of characters A constant string is enclosed in double quotes like Hello The end of the string is determined by the NULL character /0. Must be considered as an additional char (array length). VERY IMPORTANT because it is required for all string functions 2
String Example char mystr[] = Hello //requires 6 chars is equal to char mystr[6] = Hello : is equal to char mystr[6] = H, e, l, l, o, /0 ; NULL character determines end of string Strings and Pointer Because pointer and arrays have a close relation, pointer are often used together with strings. Example: char str[]= Hello students ; char *strp; strp = str; //strp refers now to str //print out Hello students printf( %s,strp); //print out llo students ; printf( %s,strp+2); //print out s, s printf %c, %c, strp[6],str[6]); 3
String operations Typical string operations are: Get the length of a string Copy a string into another Concatenate two strings Find a char or a substring within a string Compare two strings Functions doing all these are available in string.h strlen size_t *strlen(const char* str) string length returns the length of the string. The terminating null character /0 is not counted. size_t is typically defined as unsigned int. Example: char source[] = World ; int i; i = strlen(source); //i = 5 4
strcpy char *strcpy(char * dest, const char* src) string copy copies the string pointed to by src into the array pointed to by dest. The array pointed by dest must be large enough to contain the same C string as src (including the terminating null character ( /0 ). Example: char source[] = World ; char dest[6] ; strcpy(dest, source); //dest is now World (OK, 6 chars) strcat char *strcat(char * dest, const char* src) string concatenate appends a copy of source (src) to the destination string (dest). The array pointed by dest must be large enough to contain both the orginal source string and the destination string. Example: char source[]= Students char dest[15] = Hello ; strcat(dest, source); //dest is now Hello Students //(15 chars including /0 ) 5
strchr, strstr char *strchr(const char str*, int c) string character returns a pointer to the first appearance of c in str or a null pointer if c does not appear in str char *strstr(const char *s1, const char *s2) string in string returns a pointer to the first occurrence of s2 in s1, or a null pointer if s2 is not part of s1. strcmp int strcmp(const char *s1, const char *s2) string compare compare the string s1 with s2. A zero value indicates that both strings are equal. A value greater than zero indicates that the first character that does not match has a greater value in s1 than in s2. A value less than zero indicates the opposite. 6
Exercise 8 A program should allow the user to enter two strings s1 and s2. This two strings should then combined together to a new string s12. The array for the new string should have exactly the right length. Then the user can enter a third string s3. It should be checked if the string s3 is part of the new string s12. Files A file can be seen as resource for storing information. Is used by programs to store data on durable storage. A program is therefore able to open files in order to read/write data. 7
Open a file in C FILE * fopen( const char * name, const char * mode ); file open returns a so called file handle which is later used as reference (argument of other functions). name is the name of the file (including directory). mode describes the file operation mode like read, write. Example: FILE *fp: //file handle fp = fopen( myfile.txt, w ); //myfile.txt is open for writing File modes r (read): open a file for input operations. The file must exist. w (write): Create an empty pyfile for output operation. a (append): r+ (read/update): Open file for output operation. Data is appended at the end of file. File is created if it not exists. Open a file for input/output operations. The file must exist. w+ (write/update): Create an empty pyfile for input/output p operation. If the file exists it is treated as new empty file. a+ (append/update):open file for update operation. Data is always appended at the end of the file. Reposition for input operations is possible. 8
Read a character from file int fgetc(file *fp); fgetc returns the character currently ypointed by the internal file position indicator of the specified file where fp refers to. The internal file position indicator is then advanced to the next character. fp is the file handle (pointer) Returns EOF if the end of file is reached. Read a string from file char *fgets(char *string, int n, FILE *fp); fgets reads characters from file into string until (n-1) characters have been read or either a newline or the end-of-file is reached, whichever happens first. string Pointer to an array of char n is the maximum number of character which should be copied into string fp is the file handle (pointer) On success, the function returns string or NULL if no character is read (end of file) 9
Write a character to file int fputc(int c, FILE *fp); fputc writes the character c to the file and advances the position indicator. The internal file position indicator is then advanced to the next character. c The int promotion of the character to be written. The value is internally converted to an unsigned char when written. fp is the file handle (pointer) Returns the written character on success or EOF if writing fails Write a string to file int fputs(const char * string, FILE *fp); fputs writes the string gpointed to by string to file. The function begins copying from the address specified (str) until it reaches the terminating null character ('\0'). This terminating null-character is not copied to the stream. string Pointer to an array of char fp is the file handle (pointer) 10
EOF and Close File int fclose( FILE *fp); fclose closes the file where fp refers to. EOF EOF is a constant and marks the end of file. Example: fp = fopen("example.txt", "r ) if(fp!=null) c = fgetc(fp); while ( (c = fgetc(fp))!= EOF) printf("%c", c); fclose(fp); Exercise 9 A program should be created which reads in a file. The file contains a list of <string>;<int> lines like: Joachim Zumbraegel;281063 - A string has a maximum length of 50 characters - The number has a maximum of 6 digits Every line should be read in and separated into a string part and an integer part. The read values should then printed out in the following way: String[n]=<string> Int[n]=<int> Hint: (n is the line counter, starts with 1) - 11
Exercise 8 for PP #include <stdio.h> #include <malloc.h> #include <stdlib.h> #include <string.h> int main() char buffer[1024], *str[3], *str12; unsigned int i,strl; for(i=0; i < 3; i++) printf("\ninput s%d:",i+1); fflush(stdin); scanf("%s",buffer); strl = strlen(buffer)+1; str[i] = (char*)malloc(sizeof(char) * strl); strcpy(str[i], buffer); strl = strlen(str[0]) + strlen(str[1])+1; str12= (char*)(malloc(strl * sizeof(char))); strcpy(str12,str[0]); strcat(str12,str[1]); printf("\n\nnew s12 is:%s",str12); if (strstr(str12,str[2])!=null) printf("\ns3 is part of s12"); else printf("\ns3 is not part of s12"); 1
Exercise 9 for PP #include <stdio.h> #include <malloc.h> #include <stdlib.h> #include <string.h> #define BUFFERLEN 1024 int main() char buffer[bufferlength], *nump; FILE *fp; unsigned int i=1; printf("\ninput filename:"); scanf("%s",buffer); fp = fopen(buffer,"r"); if (fp!= NULL) while((fgets(buffer,bufferlen,fp))!= NULL) nump = strchr(buffer, ';'); if (nump!= NULL) *nump='\0'; printf("\nstring[%d]=%s",i,buffer); printf("\nint[%d]=%s",i++,nump+1); nump = NULL; else printf("\ncan't open %s", buffer); 2