Morteza Noferesti No explicit type, instead strings are maintained - - PowerPoint PPT Presentation

morteza noferesti no explicit type instead strings are
SMART_READER_LITE
LIVE PREVIEW

Morteza Noferesti No explicit type, instead strings are maintained - - PowerPoint PPT Presentation

Morteza Noferesti No explicit type, instead strings are maintained as arrays of characters Representing strings in C stored in arrays of characters array can be of any length end of string is indicated by a delimiter , the zero


slide-1
SLIDE 1

Morteza Noferesti

slide-2
SLIDE 2

 No explicit type, instead strings are maintained as arrays of

characters

 Representing strings in C

  • stored in arrays of characters
  • array can be of any length
  • end of string is indicated by a delimiter, the zero character ‘\0’

" A S t r in g " A \ 0 g n i r t S

slide-3
SLIDE 3

3

 String literal values are represented by sequences of

characters between double quotes (“)

 Examples

  • “” - empty string
  • “hello”

 “a” versus ‘a’

  • ‘a’ is a single character value (stored in 1 byte) as the ASCII

value for a

  • “a” is an array with two characters, the first is a, the second

is the character value \0

slide-4
SLIDE 4

4

 String literal is an array, can refer to a single

character from the literal as a character

 Example:

printf(“%c”,”hello”[1]);

  • utputs the character ‘e’

 During compilation, C creates space for each string

literal (# of characters in the literal + 1)

  • referring to the literal refers to that space (as if it is an array)
slide-5
SLIDE 5

5

 Each string literal in a C program is stored at a

different location

 So even if the string literals contain the same string,

they are not equal (in the == sense)

 Example:

  • char string1[6] = “hello”;
  • char string2[6] = “hello”;
  • but string1 does not equal string2 (they are stored at different

locations)

slide-6
SLIDE 6

6

 Allocate an array of a size large enough to hold the

string (plus 1 extra value for the delimiter)

 Examples (with initialization):

char str1[6] = “Hello”; char str2[] = “Hello”; char *str3 = “Hello”; char str4[6] = {‘H’,’e’,’l’,’l’,’o’,’\0’};

 Note, each variable is considered a constant in that the

space it is connected to cannot be changed

str1 = str2; /* not allowable, but we can copy the contents

  • f str2 to str1 (more later) */
slide-7
SLIDE 7

7  Can change parts of a string variable

char str1[6] = “hello”; str1[0] = ‘y’; /* str1 is now “yello” */ str1[4] = ‘\0’; /* str1 is now “yell” */

 Important to retain delimiter (replacing str1[5] in the

  • riginal string with something other than ‘\0’ makes a

string that does not end)

 Have to stay within limits of array

slide-8
SLIDE 8

8

 Use %s field specification in scanf to read string

  • ignores leading white space
  • reads characters until next white space encountered
  • C stores null (\0) char after last non-white space char
  • Reads into array (no & before name, array is a pointer)

 Example:

char Name[11]; scanf(“%s”,Name);

 Problem: no limit on number of characters read (need

  • ne for delimiter), if too many characters for array,

problems may occur

slide-9
SLIDE 9

9

char *str, s[] = "ALIREZA"; printf("%s", s); // ALIREZA printf(s); // ALIREZA printf("%s", s + 3); // REZA scanf("%s", s); scanf("%s", &s[0]);

slide-10
SLIDE 10

10

char *suit[ 4 ] = { "Hearts", "Diamonds", "Clubs", "Spades" };

\0 s t r a e H  suit[0] \0 s d n

  • m

a i D  suit[1] \0 s b u l C  suit[2] \0 s e d a p S  suit[3]

slide-11
SLIDE 11

11 

Empty string ""

  • Is not null pointer
  • Is not uninitialized pointer
slide-12
SLIDE 12

12

 Can use the width value in the field specification to

limit the number of characters read:

char Name[11]; scanf(“%10s”,Name);

 Remember, you need one space for the \0

  • width should be one less than size of array

 Strings shorter than the field specification are read

normally, but C always stops after reading 10 characters

slide-13
SLIDE 13

13

#include <stdio.h> void main() { char LastName[11]; char FirstName[11]; printf("Enter your name "); scanf("%10s",FirstName); printf("Nice to meet you %s\n", FirstName); }

slide-14
SLIDE 14

14

 char *gets(char *str)

 reads the next line (up to the next newline) from keyboard

and stores it in the array of chars pointed to by str

 returns str if string read or NULL if problem/end-of-file  not limited in how many chars read (may read too many

for array)

 newline included in string read

slide-15
SLIDE 15

15

 int puts(char *str)

 prints the string pointed to by str to the screen

 prints until delimiter reached (string better have a \0)

 returns EOF if the puts fails  outputs newline if \n encountered (for strings read with

gets )

slide-16
SLIDE 16

16

#include <stdio.h> int main() { char str[50]; printf("Enter a string : "); gets(str); puts(str); return(0); }

slide-17
SLIDE 17

17

 C provides a wide range of string functions for

performing different string tasks

 Examples

strlen(str) - calculate string length strcpy(dst,src) - copy string at src to dst strcmp(str1,str2) - compare str1 to str2

 Functions come from the utility library string.h

  • #include <string.h>
slide-18
SLIDE 18

18

Files

slide-19
SLIDE 19

19

 A file is a collection of related data that a

computers treats as a single unit.

 When a computer reads a file, it copies the file

from the storage device to memory; when it writes to a file, it transfers data from memory to the storage device.

 C uses a structure called FILE (defined in

stdio.h) to store the attributes of a file.

slide-20
SLIDE 20

20

  • Until now
  • We read/write data from/to terminal (console)
  • In C
  • We can read data from file
  • We can write data to file
slide-21
SLIDE 21

21

  • Main steps in working with files
  • 1) Open file
  • Get a file handler from Operating System
  • 2) Read/Write
  • Use the handler
  • 3) Close file
  • Free the handler
  • 4) Other operations
  • Check end of file, …
slide-22
SLIDE 22

22

  • Function fopen opens files

#include <stdio.h> FILE * fopen(char *name, char *mode);

  • FILE * is struct
  • Saves information about file.
  • We don’t need to know about it.
  • If cannot open file, fopen returns NULL.
  • name is the name of file:
  • Absolute name: C:\prog\test.txt
  • Relative name: Mytest.txt
slide-23
SLIDE 23

23

  • r: open for read. We cannot write to the file.
  • w: open for write. Create new file. We cannot read

form the file. If file exist, its content will be destroyed.

  • a: open for write. We cannot read form the file. If file

exist, its content wont be destroyed. We write at end of file.

slide-24
SLIDE 24

24

Mode Meaning fopen Returns if FILE- Exists Not Exists r Reading – NULL w Writing Over write on Existing Create New File a Append – Create New File r+ Reading + Writing New data is written at the beginning overwriting existing data Create New File w+ Reading + Writing Over write on Existing Create New File a+ Reading + Appending New data is appended at the end of file Create New File

slide-25
SLIDE 25

25

FILE *fp; fp = fopen("c:\test.txt", "r"); if(fp == NULL){ printf("Cannot open file\n"); return -1; }

  • Open file c:\test.txt for read
slide-26
SLIDE 26

26

  • File-Position Pointer
  • A pointer in file
  • Points to current location of read and write
  • When file is open
  • File-Position Pointer is set to start of file
  • When you read/write from/to file
  • The File-Position Pointer advance according to the size of

data

  • If you read 2 bytes, it moves 2 bytes
  • If you write 50 bytes, it advances 50 bytes
slide-27
SLIDE 27

27

  • Each opened file should be closed.
  • If we write to a file and don’t close it, some of

data will be LOST

  • To close the file

fclose(FILE *fp);

slide-28
SLIDE 28

28

  • fscanf reads from file
  • fscanf is same to scanf. Return EOF if reached
  • fprintf writes to file
  • fprintf is same to printf.

int fscanf(FILE *fp,"format", parameters); int fprintf(FILE *fp,"format", parameters);

slide-29
SLIDE 29

29

  • We have file in this format

<Number of students> <id of student 1> <grade of student 1> <id of student 2> <grade of student 2> … <id of student n> <grade of student n>

slide-30
SLIDE 30

30

#include <stdio.h> #include <stdlib.h> int main(void){ FILE *fpin; char inname[20]; int num, i, id; float sum, average, grade; printf("Enter the name of input file: "); scanf("%s", inname); fpin = fopen(inname, "r"); if(fpin == NULL){ printf("Cannot open %s\n", inname); return -1; }

‌هرمن‌و‌هرامش‌هك‌يا‌همانرب دناوخب‌لياف‌زا‌ار‌نايوجشناد‌و دنك‌هبساحم‌ار‌نيگنايم.

slide-31
SLIDE 31

31

/* Read the number of students */ fscanf(fpin,"%d", &num); /* Read the id and grade from file */ sum = 0; for(i = 0; i < num; i++){ fscanf(fpin, "%d %f", &id, &grade); sum += grade; } average = sum / num; printf("Average = %f\n", average); fclose(fpin); return 0; }

slide-32
SLIDE 32

32

#include <stdio.h> #include <stdlib.h> int main(void){ FILE *fpin, *fpout; char inname[20], outname[20]; int num, i, id; float sum, average, grade; printf("Enter the name of input file: "); scanf("%s", inname); printf("Enter the name of output file: "); scanf("%s", outname); fpin = fopen(inname, "r"); if(fpin == NULL){ printf("Cannot open %s\n", inname); return -1; }

ر‌نايوجشناد‌هرمن‌و‌هرامش‌هك‌يا‌همانرب‌ا ك‌ينايوجشناد‌تسيل‌و‌دناوخب‌لياف‌زا‌ه ار‌تسا‌نيگنايم‌زا‌رتشيب‌اهنآ‌هرمن‌رد دسيونب‌يرگيد‌لياف.

slide-33
SLIDE 33

33

fpout = fopen(outname, "w"); if(fpout == NULL){ printf("Cannot open %s\n", outname); return -1; } /* Read the number of students */ fscanf(fpin,"%d", &num); /* Read the id and grade from file */ sum = 0; for(i = 0; i < num; i++){ fscanf(fpin, "%d %f", &id, &grade); sum += grade; } average = sum / num;

slide-34
SLIDE 34

34

fclose(fpin); fpin = fopen(inname, "r"); fscanf(fpin,"%d", &num); fprintf(fpout, "%f\n", average); for(i = 0; i < num; i++){ fscanf(fpin, "%d %f", &id, &grade); if(grade >= average) fprintf(fpout, "%d: %s\n", id, "passed"); else fprintf(fpout, "%d: %s\n", id, "failed"); } fclose(fpin); fclose(fpout); return 0; }

slide-35
SLIDE 35

35

  • To write a character to file

fputc(char c, FILE *fp)

  • To read a char from file

char fgetc(FILE *fp); /*Returns EOF if reaches to End of File */

slide-36
SLIDE 36

36

#include <stdio.h> #include <stdlib.h> int main(void){ FILE *fpin, *fpout; char inname[20], outname[20]; char c; printf("Enter the name of input file: "); scanf("%s", inname); printf("Enter the name of output file: "); scanf("%s", outname); fpin = fopen(inname, "r"); if(fpin == NULL){ printf("Cannot open %s\n", inname); return -1; }

و‌يدورو‌لياف‌كي‌مسا‌هك‌يا‌همانرب ‌لياف‌و‌دريگب‌ربراك‌زا‌ار‌يجورخ دنك‌يپك‌يجورخ‌رد‌ار‌يدورو.

slide-37
SLIDE 37

37

fpout = fopen(outname, "w"); if(fpout == NULL){ printf("Cannot open %s\n", outname); return -1; } while((c = fgetc(fpin)) != EOF) fputc(c, fpout); fclose(fpin); fclose(fpout); return 0; }

slide-38
SLIDE 38

38

Checking End of File

  • Each file has two indicators
  • End of file indicator
  • Error indicator
  • These indicators are set when we want to read but there is not enough data or

there is an error

  • How to use
  • Try to read
  • If the number of read object is less than expected
  • Check end of file .. feof
  • Check error of file .. ferror
  • feof checks whether the end-of-File indicator associated

with stream is set and returns a value different from zero if it is.

slide-39
SLIDE 39

39

Checking End of File

  • Previous example with feof

while(1){ c = fgetc(fpin); if(feof(fpin)) break; fputc(c, fpout); }

slide-40
SLIDE 40

40

#include <stdio.h> int main () { FILE * pFile; int n = 0; pFile = fopen ("ss.txt","r"); while (fgetc(pFile) != EOF) { ++n; } if (feof(pFile)) { puts ("End-of-File reached."); printf ("Total number of bytes read: %d\n", n); } fclose (pFile); return 0; }

slide-41
SLIDE 41

41

Read/Write a Line (Text File)

  • We can read a line of file

char * fgets(char *buff, int maxnumber , FILE *fp);

  • Read at most maxnumber-1 chars
  • Reading stops after EOF or \n, if a \n is read it is stored

in buffer

  • Add ‘\0’ to the end of string
  • If reach to end of file without reading any character,

return NULL

slide-42
SLIDE 42

42

Read/Write a Line (Text File)

  • We can write a line to file

int fputs(char *buff, FILE *fp);

  • Write the string buff to file
  • Does NOT add \n at the end
slide-43
SLIDE 43

43

Example: Count the number of lines

char buf[500]; // 500 > every line fpin = fopen(inname, "r"); if(fpin == NULL){ printf("Cannot open %s\n", inname); return -1; } while(fgets(buf, 499, fpin) != NULL) count++; printf("Number of Lines = %d\n", count);