Morteza Noferesti
Morteza Noferesti No explicit type, instead strings are maintained - - PowerPoint PPT Presentation
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
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
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
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)
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)
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) */
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
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
9
char *str, s[] = "ALIREZA"; printf("%s", s); // ALIREZA printf(s); // ALIREZA printf("%s", s + 3); // REZA scanf("%s", s); scanf("%s", &s[0]);
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]
11
Empty string ""
- Is not null pointer
- Is not uninitialized pointer
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
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); }
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
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 )
16
#include <stdio.h> int main() { char str[50]; printf("Enter a string : "); gets(str); puts(str); return(0); }
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>
18
Files
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.
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
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, …
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
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.
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
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
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
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);
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);
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>
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; }
هرمنوهرامشهكياهمانرب دناوخبليافزاارنايوجشنادو دنكهبساحمارنيگنايم.
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; }
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; }
رنايوجشنادهرمنوهرامشهكياهمانربا كينايوجشنادتسيلودناوخبليافزاه ارتسانيگنايمزارتشيباهنآهرمنرد دسيونبيرگيدلياف.
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;
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; }
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 */
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; }
ويدوروليافكيمساهكياهمانرب ليافودريگبربراكزااريجورخ دنكيپكيجورخرداريدورو.
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; }
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.
39
Checking End of File
- Previous example with feof
while(1){ c = fgetc(fpin); if(feof(fpin)) break; fputc(c, fpout); }
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; }
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
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
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);