Universität Duisburg-Essen PRACTICAL TRAINING TO THE LECTURE Fundamentals of Programming & Procedural Programming Session Seven: Strings and Files Name: First Name: Tutor: Matriculation-Number: Group-Number: Date: Prof. Dr.Ing. Axel Hunger Dipl.-Ing. Joachim Zumbrägel Universität Duisburg-Essen Faculty of Engineering, Department Electrical Engineering and Information Technology Computer Engineering Procedural Programming/Lab7 1
Strings Strings are the form of a data type used in programming languages for storing and manipulating strings, such as words, names, and sentences. In C, a string is not a formal data type as it is in some languages. Instead it is an array of type char. When you think about it, it makes a good deal of sense, a string is a series of characters, and that is just what an array of type char is. So, we can say that, a string is a sequence of characters between a pair of double quote characters. Defining and Initializing a String A character string is basically a char array terminated with a null character (\0). A null character is a special type of a character with the code value 0 and it is added to the end of each string to mark where that string ends. A string is always terminated by a null character, so the length of a string is always one greater than the number of characters in the string. For char string[18] = "This is a string."; Here we have explicitly defined the array dimension, which is 18. 17 elements for the characters in the string plus an extra element for the terminating \0. This can be represented as follows: T h i s i s a s t r i n g. \0 Figure: Example of a string in memory. But in a case where you don t explicitly define the size, the compiler will assign a value to the dimension that is sufficient to accommodate the initializing string constant. You can specify the dimension explicitly, but if you leave it for the compiler to figure out, you can be sure it will be correct. We can use strings in a similar way as the built in data types C, so for example in order to declare a string variable name, we would have: char name[30]; Where [30] defines the size of the variable. Unlike the other built in data types like the int and the double, we can declare a string variable without initializing it and it will still be initialized as an empty string, i.e. containing zero characters. Procedural Programming/Lab7 2
char name[6]; int main( ) name[0] = H ; name[1] = E ; name[2] = L ; name[3] = L ; name[4] = O ; name[5] = \0 ; char s[4]= a, b, c, \0 ); /* example: using strings */ #include <string.h> #define MAXSTRING 30 char name[maxstring]; printf("please enter your name: "); scanf( %s, name); if (name == "") printf("you entered an empty string %s\n", name); else printf("thank you %s", name); Procedural Programming/Lab7 3
Exercise 7.1: Which of the following correctly defines a string variable and why? a. char strngvar[8] = backpack ; b. char strngvar[8]; c. char backpack ; d. strngvar[8] = backpack ; e. char strngvar[80] = rolling stone ; Procedural Programming/Lab7 4
String Handling Functions The standard C library contains a lot of special functions for further manipulation of strings. So, whenever we want to use strings or string functions in our program, we must use the standard library file for strings, as shown below: #include <string.h> There are a wide range of functions supported by the string.h library file to manipulate strings, such as: char strcpy(s1, s2); char strcat(s1, s2); int strlen(s1); int strcmp(s1, s2); char *strrev(char *string); Strcpy() char *strcpy(char *s2, const char *s1); The strcpy() function copies the string s1 into string s2. The value of s2 is returned. Note: Keep in mind, that the C language doesn t allocate additional memory for strings if you have explicitly defined it already. So, the user has to make sure the memory that they allocate to a particular string is large enough to store all the elements. For example, when using the strcpy() function like used in the example above, we need to make sure that the resulting string array i.e. s2 has enough memory space to hold all the string values after s1 has been copied into s2. Thus, memory allocation should be large enough to hold both destination and source strings. Procedural Programming/Lab7 5
/* example: using strcpy function */ #include <string.h> char s1[10] = "Hello"; char s2[12] = "World"; // copy s1 into s2 strcpy(s2, s1); printf("strcpy(s2, s1) : %s", s2); Exercise 7.2: In order to use the strcpy() library function, which one would you choose and why? a. s1.strcpy(s2); b. s2.strcpy(s1); c. strcpy(s1, s2); d. strcpy(s2, s1); e. s2 = strcpy(s1); Procedural Programming/Lab7 6
strlen(s1) size_t strlen(const char *s); The strlen()function determines the length of the given string s. The number of characters preceding the terminating null character '\0' is returned. /* example: using strlen_function */ #include <string.h> char name[10] = "Adam"; printf("the name is %u characters long.", strlen(name)); Exercise 7.3: Write a program which inputs a string and prints the length of the string. Procedural Programming/Lab7 7
strcat(s1, s2) and strncat(s1, s2) char *strcat(char *s1, const char *s2); char *strncat(char *s1, const char *s2, size_t n); The strcat() and strncat() function are used to concatenate two strings, when two strings are concatenate the contents of t he second string are copied to the end of the first string. Remember to take into account that the array string s1 is large enough to contain the original s1 string plus the string s2. strcat() function concatenates the whole string, where as strncat() function concatenates n characters of the second string. /* example: using strcat function */ #include <string.h> char string1[22] = "Electrical"; char string2[] = "Department"; strcat(string1,string2); printf("%s", string1); Procedural Programming/Lab7 8
Exercise 7.4: Write a C program which inputs a first name and a last name separately and then concatenates both into a new string. Procedural Programming/Lab7 9
Strcmp(s1, s2) and strncmp(s1, s2) functions int strcmp(const char *s1, const char *s2); int strncmp(const char *s1, const char *s2, size_t n); Strcmp() and strncmp() functions are used to compare two strings. Comparison is performed on character by character basis. Each function return a value based on the result of the comparison. The integer value returned is: = 0, if the strings are identical < 0, if the first string alphabetically precedes the second. > 0, if the second string alphabetically precedes the first. The strcmp() function compares all the characters of the first string s1 with all characters of second string s2. It returns a negative number if s1 < s2, zero if s1 == s2 or a positive number if s1 > s2. Whereas, strncmp()compares up to n characters of string s1 to s2. Returns a negative number if s1 < s2, zero if s1 == s2 or a positive number if s1 > s2. /* example: using strcmp function */ #include <string.h> char string1[] = "Electrical "; char string2[] = "Electrical"; if(strcmp(string1,string2)== 0) printf("strings are equal"); else printf("strings are not equal"); Procedural Programming/Lab7 10
strrev() function char *strrev(char *string); The strrev() function reverses the specified string. It returns a pointer to the changed string. The terminating null character remains in the same place. /* example: using strrev function */ #include <string.h> char name[] = "Hello"; printf("%s", strrev(name)); Exercise 7.6: Write a program which asks the user to input a string and then prints that string backward. Procedural Programming/Lab7 11
Files Sometimes, you need to write programs which can read from files or can write information to a file. So you might ask what is actually a file? A file is basically a named section of storage, usually on a hard disk. For example, you can think of the stdio.h, as the name of a file containing some useful information. The most commonly used operations with a file are: Opening a file Reading from a file Writing to a file Closing a file C has four basic functions to handle the above file operations: fopen() fputs() and fputc() fgets() and fgets() fclose() FILE * File I/O in C requires you to use a file pointer to the structure FILE which is defined in the stdio.h header file and which lets the program to keep track of the file being accessed. FILE *fp; // file pointer fp = fopen( my_file.txt, a ); Procedural Programming/Lab7 12
Opening a File The fopen() Function The fopen() function is used to open the file. This function is declared in the stdio.h library file. FILE *fopen(const char *file_name, const char *mode); The first argument is the name of the file to be opened; to be more exact, it s the address of a string containing that name. The second argument is a string identifying the mode in which the file is to be opened. Modes Meaning "r" "w" "a" "r+" "w+" Opens a text file for reading. Opens a text file for writing, trimming an existing file to zero length, or creating the file if it doesn t exist. Opens a text file for writing, appending to the end of an existing file, or creating the file if it doesn t exist. Opens a text file for update (that is, for both reading and writing). Opens a text file for update (reading and writing), first trimming the file to zero length if it exists or creating the file if it doesn t exist. "a+" Opens a text file for update (reading and writing), appending to the end of an existing file, or creating the file if it doesn t yet exist; the whole file can be read, but writing can only be appended. FILE *fp; fp = fopen("example.txt", "r"); Procedural Programming/Lab7 13
Closing a File The fclose() Function When you finish working with a file, you should close it. The fclose(fp) function closes the file identified by fp. int fclose(file *fp); Writing to a File The fputs() Function int fputs(const char *s, FILE *fp); The fputs()function writes a line. It writes the string value of the argument to the output stream referenced by the fp. It returns the written character written if it s successful, otherwise EOF if there is an error like if the hard disk is full or right protected. /* example: opening, writing and closing a file */ FILE *fp; fp = fopen("/gr00/example.txt", "w+"); fputs("testing the fputs function\n", fp); fclose(fp); Procedural Programming/Lab7 14
The fputc() Function int fputc(int c, FILE *fp); The fputc() function writes a character to the stream. The following example creates a file named example.txt and outputs the English alphabet from A to Z to it. /* example: using the function fputc() */ FILE *fp; char chr; fp = fopen("example.txt", "wt"); for (chr = 'A' ; chr <= 'Z' ; chr++) putc(chr, fp); fclose (fp); Procedural Programming/Lab7 15
Reading from a File The fgets() Function char *fgets(char *s, int n, FILE *fp); The fgets() function reads a line from the given stream FILE *fp and then stores it into the string pointed to by *s. The following example counts the number of lines a specified file contains. /* example: using the function fgets() */ #define LINELENGTH 100 FILE *fp; char line[linelength]; int linecount = 0; fp = fopen("example.txt","r"); while (fgets(line, LINELENGTH, fp)!= NULL) linecount++; printf("\nthe specified file contains %d lines.\n", linecount); fclose(fp); Procedural Programming/Lab7 16
The fgetc() Function int fgetc(file *fp); The fgetc() function reads a character from the input file referenced by *fp. The return value is the character read, or in case of any error it returns EOF. int fgetc(file *fp); /* example: opening, reading, and closing a file */ FILE *fp; char a; fp = fopen("example.txt", "r"); if(fp!=null) a = fgetc(fp); while (a!= EOF) printf("%c", a); a = fgetc(fp); fclose(fp); else printf("\nerror opening file!"); Procedural Programming/Lab7 17
Exercise 7.7: Write a program which compares two files, and prints the first line where they differ. Exercise 7.8: Declare and open an output file C:\example.txt and write your name, matriculation number, address and phone number onto the file C:\test.txt on separate lines. Procedural Programming/Lab7 18