Download presentation
Presentation is loading. Please wait.
1
16.216 ECE Application Programming
Instructor: Dr. Michael Geiger Fall 2013 Lecture 22 String examples File I/O
2
ECE Application Programming: Lecture 22
Lecture outline Announcements/reminders Program 6 due today Program 7 to be posted; due 11/13 Advising: 10/28 to 11/8 Review String functions Today’s lecture String examples 5/28/2018 ECE Application Programming: Lecture 22
3
Review: String functions
In <string.h> library: Copying strings: char *strcpy(char *dest, const char *source); char *strncpy(char *dest, const char *source, size_t num); Return dest Does not append ‘\0’ unless length of source < num Comparing strings: int strcmp(const char *s1, const char *s2); int strncmp(const char *s1, const char *s2, size_t num); Character-by-character comparison of character values Returns 0 if s1 == s2, 1 if s1 > s2, -1 if s1 < s2 5/28/2018 ECE Application Programming: Lecture 22
4
Review: String functions (cont.)
Find # of characters in a string size_t strlen(const char *s1); Returns # characters before ‘\0’ Not necessarily size of array “Add” strings together—string concatenation char *strcat(char *dest, const char *source); char *strncat(char *dest, const char *source, size_t num); Returns dest 5/28/2018 ECE Application Programming: Lecture 22
5
Example: Using string functions
Works with main program in PE Assume input strings have max of 49 chars (+ ‘\0’) Write a function to do each of the following: int readStrings(char *s); Repeatedly read strings from standard input until the input string matches s. Return the number of strings read. void copyNull(char *s1, char *s2, int n); Copy the first n characters of s2 into s1, and make sure that the new version of s1 terminates with a null character. int fillString(char *s, int n); Repeatedly read strings from standard input and concatenate them to s until there is no room in the string. Return the final length of the string. For example, if s is a 6-character array already holding “abcd”: User enters “e”—string is full; return 5 User enters “ef”—there’s not enough room; return 4 Assume s initially contains null terminated string (or is empty) 5/28/2018 ECE Application Programming: Lecture 22
6
ECE Application Programming: Lecture 22
Example solution int readStrings(char *s) { char str[50]; // Assume max 50 chars int count = 0; do { scanf(“%s”, str); // NOTE: do not // need &str count++; } while (strcmp(str, s) != 0); return count; } 5/28/2018 ECE Application Programming: Lecture 22
7
Example solution (cont.)
void copyNull(char *s1, char *s2, int n) { strncpy(s1, s2, n); s1[n] = ‘\0’; } 5/28/2018 ECE Application Programming: Lecture 22
8
Example solution (cont.)
int fillString(char *s, int n) { char input[50]; // Assume max // 50 chars int charsLeft; // Space remaining // in s do { scanf(“%s”, input); // Calculate # chars left in array if input // string is added. Need to leave room for ‘\0’ charsLeft = n – (strlen(s) – 1) – strlen(input); if (charsLeft > 0) // Enough space to add this string strcat(s, input); // and continue else { // Out of room if (charsLeft == 0) // Can add input, but then out of room strcat(s, input); return strlen(s); } } while (1); 5/28/2018 ECE Application Programming: Lecture 22
9
ECE Application Programming: Lecture 22
File information Name z:\Visual Studio 2010\Projects\fileio\fileio\myinput.txt Read/Write Type (binary or ASCII text) Access (security; single/multiple user) Position in file All above info is stored in a FILE type variable, pointed to by a file handle 5/28/2018 ECE Application Programming: Lecture 22
10
File i/o function calls
FILE *fopen(fname, faccess) fname: name of file (e.g., "f1.txt") faccess: up to three characters, in double quotes First char: r/w/a (read/write/append) Write starts at beginning of file, append starts at end Either write or append creates new file if none exists Second (optional) char: + (update mode) Allows both reading and writing to same file Third (optional) char: b/t (binary/text) If text files, characters may be adapted to ASCII/Unicode Binary files are just raw bytes Returns FILE address if successful; NULL otherwise 5/28/2018 ECE Application Programming: Lecture 22
11
File i/o function calls
fclose(FILE *file_handle) Closes a file Argument is address returned by fopen() Recommended for input files Required for output files O/S often doesn’t write last bit of file to disk until file is closed 5/28/2018 ECE Application Programming: Lecture 22
12
Example of basic file function usage
void main() { FILE *fp; // Open text file for reading fp = fopen("in.txt", "r"); if (fp == NULL) { printf("Error: could not open in.txt"); return; } ... // CODE TO EXECUTE IF FILE OPENS fclose(fp); // Close file when done 5/28/2018 ECE Application Programming: Lecture 22
13
File i/o function calls: formatted I/O
fprintf(file_handle, format_specifier, 0+ variables) file_handle: address returned by fopen() Other arguments are same as printf() Example: fprintf(fp, "x = %d", x); fscanf(file_handle, format_specifier, 0 or more variables) Other arguments are same as scanf() Example: fscanf(fp, "%d%d", &a, &b); 5/28/2018 ECE Application Programming: Lecture 22
14
ECE Application Programming: Lecture 22
Example: File I/O Write a program to: Read three integer values from the file myinput.txt Determine sum and average Write the original three values as well as the sum and average to the file myoutput.txt Note that: The program should exit if an error occurs in opening a file 5/28/2018 ECE Application Programming: Lecture 22
15
ECE Application Programming: Lecture 22
The program (part 1) #include <stdio.h> void main() { FILE *infile; // Input file pointer FILE *outfile; // Output file pointer int x, y, z, sum; // Input values and sum double avg; // Average of x, y, and z // Open input file, exit if error infile=fopen("myinput.txt","r"); if (infile==NULL) printf("Error opening myinput.txt\n"); return; } // Can actually open file as part of conditional statement if ((outfile=fopen("myoutput.txt","w"))==NULL) printf("Error opening myoutput.txt\n"); 5/28/2018 ECE Application Programming: Lecture 22
16
ECE Application Programming: Lecture 22
The program (part 2) // Read the three values fscanf(infile, "%d %d %d", &x, &y, &z); // Compute sum and average sum = x + y + z; avg = sum / 3.0; // print out values fprintf(outfile, "Values: %d, %d, %d\n", x, y, z); fprintf(outfile, "Sum: %d\n",sum); fprintf(outfile, "Avg: %lf\n",avg); // close the files fclose(infile); fclose(outfile); } 5/28/2018 ECE Application Programming: Lecture 22
17
ECE Application Programming: Lecture 22
Final notes Next time More string examples File I/O Reminders: Program 6 due 10/28 Advising: 10/28 to 11/8 5/28/2018 ECE Application Programming: Lecture 22
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.