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);
Character Input/Output • Read a character File *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 character fputc(c, fp); write to file putc(c, fp); same as above putchar(c); to standard output putchar(c, stdout); the same
String Input/Output • Read a string File *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 '