Strings and File I/O. CSE 251 Dr. Charles B. Owen Programming in C

Similar documents
ASCII Encoding. The char Type. Manipulating Characters. Manipulating Characters

So far we have considered only numeric processing, i.e. processing of numeric data represented

File Handling. What is a file?

System Calls and Standard I/O

Module 816. File Management in C. M. Campbell 1993 Deakin University

As previously noted, a byte can contain a numeric value in the range Computers don't understand Latin, Cyrillic, Hindi, Arabic character sets!

Sources: On the Web: Slides will be available on:

Memory management. Announcements. Safe user input. Function pointers. Uses of function pointers. Function pointer example

First Java Programs. V. Paúl Pauca. CSC 111D Fall, Department of Computer Science Wake Forest University. Introduction to Computer Science

The C Programming Language course syllabus associate level

KITES TECHNOLOGY COURSE MODULE (C, C++, DS)

CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013

C Strings and Pointers

5 Arrays and Pointers

Lex et Yacc, exemples introductifs

Basic Java Constructs and Data Types Nuts and Bolts. Looking into Specific Differences and Enhancements in Java compared to C

Chapter 13 Storage classes

C Examples! Jennifer Rexford!

Embedded Systems Design Course Applying the mbed microcontroller

Introduction to Programming II Winter, 2014 Assignment 2

Scoping (Readings 7.1,7.4,7.6) Parameter passing methods (7.5) Building symbol tables (7.6)

CSE 1223: Introduction to Computer Programming in Java Chapter 2 Java Fundamentals

Chapter 2: Elements of Java

Introduction to Java. CS 3: Computer Programming in Java

GUJARAT TECHNOLOGICAL UNIVERSITY, AHMEDABAD, GUJARAT COURSE CURRICULUM. Course Title: Advanced Computer Programming (Code: )

Simple C Programs. Goals for this Lecture. Help you learn about:

MATLAB: Strings and File IO

8.5. <summary> Cppcheck addons Using Cppcheck addons Where to find some Cppcheck addons

Illustration 1: Diagram of program function and data flow

How To Port A Program To Dynamic C (C) (C-Based) (Program) (For A Non Portable Program) (Un Portable) (Permanent) (Non Portable) C-Based (Programs) (Powerpoint)

public static void main(string[] args) { System.out.println("hello, world"); } }

Introduction to Data Structures

Lexical Analysis and Scanning. Honors Compilers Feb 5 th 2001 Robert Dewar

Basics of I/O Streams and File I/O

MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question.

C++ INTERVIEW QUESTIONS

Informatica e Sistemi in Tempo Reale

Object-Oriented Design Lecture 4 CSU 370 Fall 2007 (Pucella) Tuesday, Sep 18, 2007

Lecture 5: Java Fundamentals III

Compiler Construction

Semantic Analysis: Types and Type Checking

Handout 3 cs180 - Programming Fundamentals Spring 15 Page 1 of 6. Handout 3. Strings and String Class. Input/Output with JOptionPane.

1 Abstract Data Types Information Hiding

1001ICT Introduction To Programming Lecture Notes

Lab 4.4 Secret Messages: Indexing, Arrays, and Iteration

Chapter 13 - The Preprocessor

Object-Oriented Programming in Java

El Dorado Union High School District Educational Services

C++ Outline. cout << "Enter two integers: "; int x, y; cin >> x >> y; cout << "The sum is: " << x + y << \n ;

Tutorial on C Language Programming

Unit Write iterative and recursive C functions to find the greatest common divisor of two integers. [6]

CS 106 Introduction to Computer Science I

Lecture 11 Doubly Linked Lists & Array of Linked Lists. Doubly Linked Lists

Masters programmes in Computer Science and Information Systems. Object-Oriented Design and Programming. Sample module entry test xxth December 2013

Java Basics: Data Types, Variables, and Loops

Handout 1. Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner.

How To Write Portable Programs In C

CS193D Handout 06 Winter 2004 January 26, 2004 Copy Constructor and operator=

CP Lab 2: Writing programs for simple arithmetic problems

arrays C Programming Language - Arrays

A Grammar for the C- Programming Language (Version S16) March 12, 2016

System Calls Related to File Manipulation

Introduction to Java

Formatting Numbers with C++ Output Streams

Embedded Systems. Review of ANSI C Topics. A Review of ANSI C and Considerations for Embedded C Programming. Basic features of C

Stacks. Linear data structures

C Interview Questions

PL / SQL Basics. Chapter 3

Lab 4: Socket Programming: netcat part

C Programming. for Embedded Microcontrollers. Warwick A. Smith. Postbus 11. Elektor International Media BV. 6114ZG Susteren The Netherlands

C PROGRAMMING FOR MATHEMATICAL COMPUTING

Free Java textbook available online. Introduction to the Java programming language. Compilation. A simple java program

Computer Science Questions and Answers UNIT-A Chapter - 1 Configuring a Computer

Software security. Buffer overflow attacks SQL injections. Lecture 11 EIT060 Computer Security

Free Java textbook available online. Introduction to the Java programming language. Compilation. A simple java program

Keywords are identifiers having predefined meanings in C programming language. The list of keywords used in standard C are : unsigned void

XMOS Programming Guide

This section describes how LabVIEW stores data in memory for controls, indicators, wires, and other objects.

IPC. Semaphores were chosen for synchronisation (out of several options).

Chulalongkorn University International School of Engineering Department of Computer Engineering Computer Programming Lab.

Package HadoopStreaming

CS107L Handout 02 Autumn 2007 October 5, 2007 Copy Constructor and operator=

CS 241 Data Organization Coding Standards

X86-64 Architecture Guide

C / C++ and Unix Programming. Materials adapted from Dan Hood and Dianna Xu

SQL is capable in manipulating relational data SQL is not good for many other tasks

DESIGN: A Program to Create Data Entry Programs

EXEC SQL CONNECT :userid IDENTIFIED BY :passwd;

Passing 1D arrays to functions.

Classes and Objects in Java Constructors. In creating objects of the type Fraction, we have used statements similar to the following:

1) Which of the following is a constant, according to Java naming conventions? a. PI b. Test c. x d. radius

Computer Programming I

FEEG Applied Programming 5 - Tutorial Session

Object Oriented Software Design II

1 Posix API vs Windows API

COMPUTER SCIENCE 1999 (Delhi Board)

Computer Programming Tutorial

Lab 1: Introduction to C, ASCII ART and the Linux Command Line Environment

Introduction to Information Security

Transcription:

Strings and File I/O 1

Character Type: char In C, characters are indicated by single quotes: The type is char for char mychar; one (1) character mychar = 'a'; printf( mychar is %c\n, mychar); %c is the formal specifier for a char 2

String A string is an array of characters, it is indicated by double quotes: "this is a string" But you can t use an assignment operator to assign a string to a character array char mychar[80]; /* array of chars */ mychar[4] = a ; /* OK */ mychar = this is a string ; /* NOT OK */ 3

String t A null ( \0 ) character is placed to mark the end of each string h i s i s a s t r i n g \0 String functions use \0 to locate end of string (so you don t have to pass string length as argument to the functions) 4

Initializing a String char mystr[5] = { a, b, c, d, 0}; printf( mystr is %s\n, mystr); mystr a b c d \0 Array size has exactly 5 elements A terminating \0 character at the end (in ASCII, char \0 is equivalent to int 0) Will print: mystr is abcd 5

Another way char mystr[10]= birdbath ; printf( mystr is %s\n, mystr); mystr b i r d b a t h \0 Ok to use assignment only to initialize string mystr is an array of 10 characters (but only the first 8 elements used to store the word) a \0 is added to the end automatically (so 9 elements in the array are occupied) id) 6

Better way mystr char mystr[]= birdbath ; printf( mystr is %s\n, mystr); b i r d b a t h \0 \0 is added automatically to the end of mystr Space is allocated automatically ti to hold exactly what htwe need (9 locations, including \0 ) 7

printf for Strings char mystr[] = abc123 ; Output: Use %s to print the entire string: printf( %s\n,mystr); /* outputs abc123 */ /* \0 is not printed */ Use %c to print a character: printf( %c\n,mystr[1]); /* outputs: b */ 8

String input There are several functions available Part of the stdio.h library. 9

scanf scanf reads up to the first white space, ignores the stuff typed in after that. Be careful when using it. char mystr[10]; printf( Enter a string: ); scanf( %s, mystr); printf( You entered %s\n\n, mystr) 10

scanf safer Use %[width]s to copy only up to a maximum number of character. But, does not append the \0 char mystr[10]; printf( Enter a string: ); scanf( %9s, mystr); mystr[9] = \0 ; /* Do this yourself just in case */ printf( You entered %s\n\n, mystr) 11

getchar getchar will fetch one (1) character from the input stream char mychar; printf( Enter a character: ); mychar = getchar(); printf( You entered %c\n\n, mychar); 12

fgets char * fgets(chararray, lengthlimit, fileptr) fetches a whole line, up to the size limit or when it sees a new line It will add a \0 at the end of string Example: char mystr[80]; fgets(mystr, 80, stdin); // fetch from console Returns a NULL if something went wrong, otherwise a pointer to the array The functions that start with f work with any source of input. stdin is the C Standard Input. 13

#include<stdio.h> #include<string.h> int main () { int inputlength=20 int cnt=0; char str1[20], str2[20]; } printf("\nenter a string: "); fgets(str1, inputlength, stdin); printf("you entered %s\n",str1); printf( Enter another string: "); scanf("%s",str2); printf("you entered %s\n",str2); Make sure you re clear the difference between fgets and scanf 14

str1 (read using fgets) t Note the extra new line when using fgets h i s i s a s t r i n g \n \0 str2 (read using scanf) t h i s \0 15 1

String manipulation functions strcpy Copies a string strcat Concatenates two strings strlen Returns the length of a string strcmp Compares two strings #include <string.h> 16

string copy (strcpy) strcpy(deststring, srcstring); char [] strcpy (char dest[], const char src[]); copy string contents from src (2 nd arg) to dest (1 st arg) including \0 dest is changed, src unmodified (but can do some weird things) returns a pointer to the modified dest array 17

string copy (strcpy) char [] strcpy (char dest[], const char src[]); There is no error checking! If dest array is shorter than src array, no errors. Weird things could happen, but no compile errors and often no runtime errors Tracking these bugs down is very hard! 18

Safer version of string copy strncpy(deststring, srcstring, 80); char [] strncpy (char dest[], const char src[], int N); copies at most N characters from src to dest (or up to \0 If length of src is greater than N, copies only the first N characters If length of src is less than N, pad the remaining elements in dest with \0 Does not copy the \0 if the string length is >= N 19

concatenation (strcat) char [] strcat(char dest[], const char src[]) contents of src are added to the end of dest. dest is changed, src is not \0 added to the end of dest return a pointer to dest no bounds check (again, this is C) 20

comparison (strcmp) int strcmp (const char s1[], const char s2[]); Compares 2 strings if s1 precedes s2, return value is less than 0 if s2 precedes s1, return value is greater than 0 if s1 equal to s2, return value is 0 Comparison is based on lexicographic order (ASCII order) e.g., a < b 21

#include <stdio.h> #include <string.h> int main() { printf("strcmp(\"a\",\"b\"): %d\n", strcmp("a","b")); printf("strcmp(\"b\",\"a\"): %d\n", strcmp("b""a"));, printf( strcmp(\"a\",\"a\"): %d\n", strcmp("a","a")); printf("strcmp(\"2\",\"3\"): %d\n", strcmp("2","3")); printf("strcmp(\"2\",\"10\"): %d\n", strcmp("2","10")); } Lexicographic ordering is not the same as ordering numbers 22

Reversing a string Input: Math is fun Output: nuf si htam How would you do this? 23

front void Reverse(char str[] ) { int front = 0; int back = strlen(str) 1; char t; /* A temporary place to put a character */ back } while (front < back) { t = str[front]; str[front] = str[back]; str[back] = t; front++; back ; } 24 2

Built in in functions for characters #include <ctype.h> These all return boolean (1/0). isalnum(c): is c alphanumeric? isalpha(c): is c alphabetic? isdigit(c): is c a digit? iscntrl(c): is c a control character? islower(c): is c lower case? isupper(c): is c upper case? ispunct(c): is c a punctuation character, that is a printable character that is neither a space nor an alphanumeric character 25

converters char tolower(c) return the character as lower case char toupper(c) return the character as upper case 26

File IO How to write programs to read from or write to files So far, we ve only looked at how to read/write to the console 27

Open files Files are opened with fopen the fopen function is part of stdio.h It takes two args: a string (the name of a file) and a mode string (how the file is opened). It returns a file pointer fptr = fopen( myfile.txt, r ); 28

Declare and assign file pointer fopen returns a NULL pointer if it cannot perform the operation FILE *infile; infile = fopen( file.txt, r ); t r ) if (infile == NULL) // bad file opening 29

file modes r, read from the beginning of an existing file w, make an empty file (wipe out old contents), start writing. a, find an existing file, start writing at the end of that file 30

Close files Files are closed with fclose the fclose function is part of stdio.h It takes one argument: pointer to the file to be closed fclose(fptr); 31

The f functions most of the I/O functions we know have an equivalent f version to work with a file. The first argument is the file pointer value of an opened file fprintf(fileptr, format string, values) fscanf(fileptr, format string, addresses) feof(fileptr) f(fil end of file test t 32 3