Fundamentals of Programming & Procedural Programming

Similar documents
Procedural Programming

File I/O. Arash Rafiey. November 7, 2017

Programming in C. Session 7. Seema Sirpal Delhi University Computer Centre

File IO and command line input CSE 2451

ONE DIMENSIONAL ARRAYS

Strings. Arrays of characters. Pallab Dasgupta Professor, Dept. of Computer Sc & Engg INDIAN INSTITUTE OF TECHNOLOGY

Create a Program in C (Last Class)

Administrative Stuff. More on Strings, File I/O. Last Time. Java API

More on Strings, File I/O. September 8, 2016

Characters and Strings

C for Engineers and Scientists: An Interpretive Approach. Chapter 14: File Processing

Computer Programming: Skills & Concepts (CP) Strings

C programming basics T3-1 -

Fundamentals of Programming & Procedural Programming

Programming in C. Session 8. Seema Sirpal Delhi University Computer Centre

SYSC 2006 C Winter String Processing in C. D.L. Bailey, Systems and Computer Engineering, Carleton University

Introduction to file management

Engineering program development 7. Edited by Péter Vass

CSC209H Lecture 4. Dan Zingaro. January 28, 2015

CS246 Spring14 Programming Paradigm Files, Pipes and Redirection

8. Characters, Strings and Files

BIL 104E Introduction to Scientific and Engineering Computing. Lecture 12

Introduction to string

CSCE150A. Introduction. Basics. String Library. Substrings. Line Scanning. Sorting. Command Line Arguments. Misc CSCE150A. Introduction.

Procedural Programming & Fundamentals of Programming

Computer Science & Engineering 150A Problem Solving Using Computers. Chapter 9. Strings. Notes. Notes. Notes. Lecture 07 - Strings

Organization of a file

C mini reference. 5 Binary numbers 12

Computer Science & Engineering 150A Problem Solving Using Computers

Standard C Library Functions

Course organization. Course introduction ( Week 1)

Procedural Programming

System Software Experiment 1 Lecture 7

Content. Input Output Devices File access Function of File I/O Redirection Command-line arguments

Iosif Ignat, Marius Joldoș Laboratory Guide 9. Character strings CHARACTER STRINGS

B.V. Patel Institute of Business Management, Computer & Information Technology, Uka Tarsadia University

C Input/Output. Before we discuss I/O in C, let's review how C++ I/O works. int i; double x;

C Style Strings. Lecture 11 COP 3014 Spring March 19, 2018

Using Character Arrays. What is a String? Using Character Arrays. Using Strings Life is simpler with strings. #include <stdio.

Chapter 9 Strings. With this array declaration: char s[10];

ARRAYS(II Unit Part II)

Reading Assignment. Strings. K.N. King Chapter 13. K.N. King Sections 23.4, Supplementary reading. Harbison & Steele Chapter 12, 13, 14

C-Refresher: Session 10 Disk IO

Chapter 5. Section 5.4 The Common String Library Functions. CS 50 Hathairat Rattanasook

Computers Programming Course 11. Iulian Năstac

M.CS201 Programming language

Chapter 8: Character & String. In this chapter, you ll learn about;

Lecture07: Strings, Variable Scope, Memory Model 4/8/2013

upper and lower case English letters: A-Z and a-z digits: 0-9 common punctuation symbols special non-printing characters: e.g newline and space.

Introduction to C/C++ Lecture 5 - String & its Manipulation

LECTURE 15. String I/O and cstring library

Eastern Mediterranean University School of Computing and Technology Information Technology Lecture7 Strings and Characters

Lecture 05 Pointers ctd..

Strings in C++ Dr. Ferdin Joe John Joseph Kamnoetvidya Science Academy

CS113: Lecture 7. Topics: The C Preprocessor. I/O, Streams, Files

C Characters and Strings

Eastern Mediterranean University School of Computing and Technology Information Technology Lecture5 C Characters and Strings

CMPE-013/L. File I/O. File Processing. Gabriel Hugh Elkaim Winter File Processing. Files and Streams. Outline.

CE Lecture 11

Strings(2) CS 201 String. String Constants. Characters. Strings(1) Initializing and Declaring String. Debzani Deb

ECE551 Midterm Version 2

Day14 A. Young W. Lim Tue. Young W. Lim Day14 A Tue 1 / 15

Fundamentals of Programming & Procedural Programming

C Programming Language Review and Dissection III

C: Arrays, and strings. Department of Computer Science College of Engineering Boise State University. September 11, /16

ECE551 Midterm Version 1

Arrays, Strings, & Pointers

Lecture 7: Files. opening/closing files reading/writing strings reading/writing numbers (conversion to ASCII) command line arguments

Input/Output and the Operating Systems

fopen() fclose() fgetc() fputc() fread() fwrite()

CSE 230 Intermediate Programming in C and C++ Arrays, Pointers and Strings

C strings. (Reek, Ch. 9) 1 CS 3090: Safety Critical Programming in C

Standard File Pointers

Chapter 8 - Characters and Strings

Procedural Programming & Fundamentals of Programming

Input / Output Functions

CSE2301. Introduction. Streams and Files. File Access Random Numbers Testing and Debugging. In this part, we introduce

mith College Computer Science CSC270 Spring 2016 Circuits and Systems Lecture Notes, Week 11 Dominique Thiébaut

CSC 2400: Computer Systems. Arrays and Strings in C

Pointers, Arrays, and Strings. CS449 Spring 2016

C Basics And Concepts Input And Output

CS 137 Part 6. ASCII, Characters, Strings and Unicode. November 3rd, 2017

Characters in C consist of any printable or nonprintable character in the computer s character set including lowercase letters, uppercase letters,

Overview. Concepts this lecture String constants Null-terminated array representation String library <strlib.h> String initializers Arrays of strings

File Access. FILE * fopen(const char *name, const char * mode);

PROGRAMMAZIONE I A.A. 2017/2018

211: Computer Architecture Summer 2016

Procedural Programming & Fundamentals of Programming

CSC 2400: Computer Systems. Arrays and Strings in C


7/21/ FILE INPUT / OUTPUT. Dong-Chul Kim BioMeCIS UTA

Lecture 10 Arrays (2) and Strings. UniMAP SEM II - 11/12 DKT121 1

Programming Fundamentals

ECE551 Midterm. There are 7 questions, with the point values as shown below. You have 75 minutes with a total of 75 points. Pace yourself accordingly.

gcc hello.c a.out Hello, world gcc -o hello hello.c hello Hello, world

Day14 A. Young W. Lim Thr. Young W. Lim Day14 A Thr 1 / 14

C++ Arrays. Arrays: The Basics. Areas for Discussion. Arrays: The Basics Strings and Arrays of Characters Array Parameters

C: How to Program. Week /May/28

ECE551 Midterm Version 1

Character Arrays. strlen("hello, world"); /* string constant */ strlen(array); /* char array[100]; */ strlen(ptr); /* char *ptr; */

Transcription:

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