opening and closing files first define a file pointer, which can "pointing" to one of the...

16
Opening and Closing Files First define a file pointer, which can "pointing" to one of the opened file. #include <stdio.h> . . . FILE *fp; Use fopen() to open a file, which returns a file pointer. fp = fopen(name, mode); where name is a string for the file's name, and mode is a string among "r" (for read only), "w" (for write only), etc. Close the file with fclose(fp);

Upload: gregory-wade

Post on 03-Jan-2016

215 views

Category:

Documents


3 download

TRANSCRIPT

Page 1: Opening and Closing Files First define a file pointer, which can "pointing" to one of the opened file. #include... FILE *fp; Use fopen() to open a file,

Opening and Closing Files

• First define a file pointer, which can "pointing" to one of the opened file.#include <stdio.h>. . .FILE *fp;

• Use fopen() to open a file, which returns a file pointer.fp = fopen(name, mode);

where name is a string for the file's name, and mode is a string among "r" (for read only), "w" (for write only), etc.

• Close the file withfclose(fp);

Page 2: Opening and Closing Files First define a file pointer, which can "pointing" to one of the opened file. #include... FILE *fp; Use fopen() to open a file,

Use files

#include <stdio.h>#define RECORD_LENGTH 60main(){ FILE *fp; char s[RECORD_LENGTH+1];

if( (fp = fopen("PORTFOLIO.DAT", "r")) == NULL) printf("Cannot open file!\n"); else { while( fgets(s, RECORD_LENGTH+1, fp) != NULL) printf("\n%s", s); fclose(fp); }}

Page 3: Opening and Closing Files First define a file pointer, which can "pointing" to one of the opened file. #include... FILE *fp; Use fopen() to open a file,

Character Input/Output

• Read a characterFile *fp;char c;fp = fopen(. . .);c = fgetc(fp); from file

c = getc(fp); same as above

c = getchar(); from standard input

c = fgetc(stdin); same as above

• Write a characterfputc(c, fp); write to file

putc(c, fp); same as above

putchar(c); to standard output

putchar(c,stdout); the same

Page 4: Opening and Closing Files First define a file pointer, which can "pointing" to one of the opened file. #include... FILE *fp; Use fopen() to open a file,

StringInput/Output

• Read a stringFile *fp;char s[80];fgets(s, 80, fp); Read from file up to 79 characters or when newline

is reached, '\n' included in the string. fgets appends the null character '\0'.

gets(s); Read from standard input until newline, the '\n'

character is not included in s. Null character appended.

• Write a stringfputs(s, fp); write to file all characters in s up to (but not include)

the null character.

puts(s); Write to standard output in s up to (but not include)

the null character. A newline character is appended to the string.

Page 5: Opening and Closing Files First define a file pointer, which can "pointing" to one of the opened file. #include... FILE *fp; Use fopen() to open a file,

Formatted Input

• scanf(format_str, pt1, pt2,…) read from standard input.

• fscanf(fp, format_str, pt1, pt2, …) read from a file

• sscanf(str, format_str, pt1, pt2, …) read from a string str.

– Where format_str is a string containing descriptor %code, the conversion code can be d (for integer), c (for character), s (for string), f (for floating point number), etc.

– pt1, pt2, …, are pointers (addresses) associated with each format descriptor.

– fp is file pointer.

Page 6: Opening and Closing Files First define a file pointer, which can "pointing" to one of the opened file. #include... FILE *fp; Use fopen() to open a file,

Input Format Descriptors

#include <stdio.h>main(){ char s[3], t[30], u[30]; int i; float f;

scanf("%c", s); scanf(" %2d%4s%4f", &i, t, &f); scanf(" \"%[^\"]\"", u); printf("%d, %f, %c, %s, %s\n", i, f, s[0], t, u);}

Input:a44mice2.97 "string"

Output:44, 2.970000, a, mice, string

Page 7: Opening and Closing Files First define a file pointer, which can "pointing" to one of the opened file. #include... FILE *fp; Use fopen() to open a file,

Formatted Output

• printf(format_str, v1, v2,…) write to standard input.

• fprintf(fp, format_str, v1, v2, …) write to a file

• sprintf(str, format_str, v1, v2, …) write a string str.

– Where format_str is a string containing descriptor %code, the conversion code can be d (for integer), c (for character), s (for string), f (for floating point number), p (for addresses), etc.

– v1, v2, …, are variables (values) associated with each format descriptor.

– fp is file pointer.

Page 8: Opening and Closing Files First define a file pointer, which can "pointing" to one of the opened file. #include... FILE *fp; Use fopen() to open a file,

Output Descriptors

#include <stdio.h>main(){ char big_A = 'A'; char s[] = "look"; int sevens = 7777777; double pi = 3.14159265; 12345678901234567 printf("\n%d", big_A); 65 printf("\n%c", 61); = printf("\n%x", sevens); 76adf1 printf("\n%c", big_A); A printf("\n%5c", big_A); A printf("\n%-5c", big_A); A printf("\n%10s", s); look printf("\n%-10s", s); look printf("\n%f", pi); 3.141593 printf("\n%5.3f", pi); 3.142 printf("\n%.15f", pi); 3.141592650000000 printf("\n%-15.3f", pi); 3.142 printf("\n%15.3f", pi); 3.142}

Page 9: Opening and Closing Files First define a file pointer, which can "pointing" to one of the opened file. #include... FILE *fp; Use fopen() to open a file,

Unformatted I/O#include <stdio.h>main(){ float v[5], r[5]; FILE *fp;

v[0] = 13.15; v[1] = 1.0;

fp = fopen("test.dat", "wb"); fwrite(v, sizeof(float), 2, fp); fclose(fp);

fp = fopen("test.dat", "rb"); fread(r, sizeof(float), 2, fp); fclose(fp);

printf("%f %f\n", r[0], r[1]);}

The print out is:13.150000 1.000000In the file text.dat we haveffRA… which is the characters for hexadecimal number 66 66

52 41, which in turn is the IEEE representation of 13.15.

Page 10: Opening and Closing Files First define a file pointer, which can "pointing" to one of the opened file. #include... FILE *fp; Use fopen() to open a file,

Real World Application:An interactive calculator

ProblemImplement an interactive calculator that simulates the hand-held kind.(page 406)

Header file defines.h

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

#define MaxExp (120)#define Forever (1)#define False (0)#define Stop '!'

Page 11: Opening and Closing Files First define a file pointer, which can "pointing" to one of the opened file. #include... FILE *fp; Use fopen() to open a file,

Top of the Calc.c

#include "defines.h"

/* The interactive calculator simulates a hand-held calculator. The calculator evaluates expressions until the user signals halt. An expression consists of a left operand, an operator, and a right operand. The left operand is initialized to zero and is automatically displayed as part of the prompt for user input. The user inputs the right operand, an expression that consists of constants and operators. To halt, the user enters the stop character '!' as the first operator in the right operand.*/

int lhs = 0; /* Left-hand side */char buffer[MaxExp+2]; /* I/O buffer */static char* ops = "+-*/%!";

void prompt(void), input (void), output (void), update_lhs(void);int bad_op(char);

Page 12: Opening and Closing Files First define a file pointer, which can "pointing" to one of the opened file. #include... FILE *fp; Use fopen() to open a file,

The main() and a function bad_op()

main(){ while(Forever) { prompt(); input(); output(); }}

int bad_op(char c){ return NULL == strchr(ops, c);

}

Page 13: Opening and Closing Files First define a file pointer, which can "pointing" to one of the opened file. #include... FILE *fp; Use fopen() to open a file,

The Parsing function

void update_lhs(void){ char *next = buffer, *last; char op[10], numStr[20]; int num; int temp = lhs;

last = next + strlen(buffer); while (next < last) { if ( sscanf(next, "%s %s", op, numStr) < 2 || strlen(op) != 1 || bad_op(op[0]) ) return; if (Stop == op[0] ) { printf(" *** End of Calculation ***\n\n"); exit(EXIT_SUCCESS); } num = atoi(numStr);

switch(op[0]) { case '+': temp += num; break; case '-': temp -= num; break; case '*': temp *= num; break; case '/': temp /= num; break; case '%': temp %= num; break; }

next += strlen(op) + strlen(numStr) + 2; } lhs = temp;}

Page 14: Opening and Closing Files First define a file pointer, which can "pointing" to one of the opened file. #include... FILE *fp; Use fopen() to open a file,

The io.c

#include "defines.h"

void update_lhs(void);

extern char buffer[MaxExp+2];extern int lhs;

void prompt(void){ printf("\n%d ", lhs);}

void input(void){ char * nl; fgets(buffer, MaxExp, stdin); if ( (nl = strchr(buffer, '\n') ) != NULL) *nl = '\0'; /* eliminate new line */}void output(void){ printf("%d %s == ", lhs, buffer); update_lhs(); printf("%d\n", lhs);}

Page 15: Opening and Closing Files First define a file pointer, which can "pointing" to one of the opened file. #include... FILE *fp; Use fopen() to open a file,

Running the Program

0 + 44 * 3 / 2 input0 + 44 * 3 / 2 == 66 output

66 % 566 % 5 == 1

1 + 100 * 3 / 21 + 100 * 3 / 2 == 151

151 * 18 + 345 - 99151 * 18 + 345 - 99 == 2964

2964 ! Anything2964 ! Anything == **** End of Calculation ****

Page 16: Opening and Closing Files First define a file pointer, which can "pointing" to one of the opened file. #include... FILE *fp; Use fopen() to open a file,

Reading/Home Working

• Read Chapter 9, page 438 to 469.

• Work on Problems– Section 9.1, page 440,

exercise 1, 3, 5.– Section 9.4, page 449,

exercise 1, 3.– Section 9.5, page 463,

exercise 1, 3.

• Check your answers in the back of the textbook. Do not hand in.