Download as pdf or txt
Download as pdf or txt
You are on page 1of 6

CS 354 - Machine Organization

Wednesday, September 21, 2016

Homework hw2 (1.5%) due 10 pm Tuesday, September 27th


Project p2 (6%) assigned tonight

Last Time
Return Values and Pointers
Parameter and Return Value Caveats
Structures
Nested structs and Arrays of structs
Today
Pointers to structs (from last time)
Strings and string.h.
Standard & String I/O and stdio.h
File I/O and stdio.h
Next Time
Read: B&O 9.9.1 - 9.9.2
C Abstract Memory Model
Address Space Layout
Dynamic Memory Intro

Copyright 2016 Jim Skrentny

CS 354 (F16): L7 - 1

Strings
What?

How?

 Declare a string variable, named str1, and initialize it with CS 354.

 Draw a memory diagram of str1.

 Declare a string pointer, named sptr1, and initialize it with CS 354.

 Draw a memory diagram of sptr1.

 If each of the following code fragments is in a main function with necessary #includes
what happens when the code is attempted to be compiled and run?
1.

2.

3.

4.

Copyright 2016 Jim Skrentny

CS 354 (F16): L7 - 2

string.h Library
What?

int strlen(const char *str)

Returns the length of string str up to but not including the null character.

char *strcpy(char *dest, const char *src)

Copies the string pointed to by src to the memory pointed to by dest.

char *strcat(char *dest, const char *src)


Appends the string pointed to by src to the end of the string pointed to by dest.

int strcmp(const char *str1, const char *str2)

Compares the string pointed to by str1 to the string pointed to by str2.

Copyright 2016 Jim Skrentny

CS 354 (F16): L7 - 3

Standard and String I/O in stdio.h Library


Standard I/O
Standard Output (console)
putchar, puts
int printf(const char *format, ...)

Standard Input (keyboard)


getchar, gets
int scanf(const char *format, ...)

Standard Error (console)


void perror(const char *str)

String I/O
int sprintf(char *str, const char *format, ...)

int sscanf(const char *str, const char *format, ...)

Copyright 2016 Jim Skrentny

CS 354 (F16): L7 - 4

File I/O in stdio.h Library


Standard I/O Redirection

File I/O
File Output
fputc/putc, fputs
int fprintf(FILE *stream, const char *format, ...)

File Input
fgetc/getc, ungetc, fgets
int fscanf(FILE *stream, const char *format, ...)

File Pointers

stdin, stdout, stderr

Opening/Closing
FILE *fopen(const char *filename, const char *mode)

int fclose(FILE *stream)

Copyright 2016 Jim Skrentny

CS 354 (F16): L7 - 5

Copying Text Files

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[]) {


if (argc != 3) {
fprintf(stderr, "Usage: copy inputfile outputfile\n");
exit(1);
}

FILE *ifp, *ofp;


ifp =
if (ifp == NULL) {
fprintf(stderr, "Can't open input file %s!\n", argv[1]);
exit(1);
}
ofp =
if (ofp == NULL) {
fprintf(stderr, "Can't open output file %s!\n", argv[2]);
exit(1);
}

const int bufsize = 257;


char buffer[bufsize];

return 0;
}

Copyright 2016 Jim Skrentny

CS 354 (F16): L7 - 6

You might also like