Presentation is loading. Please wait.

Presentation is loading. Please wait.

Plan for the Day: I/O (beyond scanf and printf)

Similar presentations


Presentation on theme: "Plan for the Day: I/O (beyond scanf and printf)"— Presentation transcript:

1 Plan for the Day: I/O (beyond scanf and printf)
Input and Output Topic 7 Plan for the Day: I/O (beyond scanf and printf)

2 Standard, String and File I/O

3 I/O in C Input and output facilities provided by standard library <stdio.h> and not by the language Text stream consists of series of lines ending with '\n'

4 Standard Input & Output
int putchar(int c) prints char c to stdout Returns c, or EOF on error int getchar() Returns next character from stdin Returns EOF on error EOF = end of file character

5 Standard I/O #include<stdio.h> int main() { char c; printf("Enter a character: "); c = getchar(); printf("Character entered was: "); putchar(c); } CExamples/IOExamples/getPutChar.c

6 Standard Input & Output
What does this do? int main() { char c; while((c = getchar()) != EOF) { if(c >= 'A' && c <= 'Z') c = c – 'A' + 'a'; putchar(c); } return 0; In Unix: to use a file instead of stdin, use < operator Input redirection: ./a.out < file.txt Treats file.txt as source of standard input Ctrl-Z or Ctrl-D or Ctrl-C to produce EOF (depending on OS) CExamples/IOExamples/testGetChar.c

7 String Input/Output Write formatted output to a string:
int sprintf(char str[], char format[], arg-list) Format specification same as printf Output written to str, size not checked Returns # of characters written (excluding '\0') or negative value on error Read formatted input from a string: int sscanf(char str[], char format[], var-address-list) format specification same as scanf Input read from str Returns # of variables filled or EOF on error Remember that scanf, sscanf, fscanf leaves behind any \n on the input stream Also: scanf automatically put null at end of input string printf, puts assume output string ends with null Make scanf safer by using the conversion specifier %ns, where n specifies max number of chars to be read CExamples/IOExamples/sprintfEx.c, sprintfEx2.c

8 Example Example: int age; char name[20]; char str[80] = "Sarah 23"; sscanf(str, "%s %d", name, &age); printf("Name: %s, age: %d\n", name, age); Example: Use sprintf to convert a double into an array of characters: char answer[100]; double number = ; sprintf(answer, "%f", number); printf("%c\n", answer[0]); Output: Name: Sarah, age: 23 Code: CExamples/IOExamples/sscanfFun.c If I print the return value of sscanf, I'll get 2 Exercise: Change this example so I make sure not to read too long a string into name Read from str Print to answer Output: 9

9 Files Open a text or binary file:
FILE* fopen(char name[], char mode[]) modes: "r" (read only), "w" (write only), "a" (append). Append "b" for binary files Returns pointer to file if it exists, NULL otherwise (creates new file for mode "w") Close stream: int fclose(FILE* fp) fclose() automatically called on all open files when program terminates CExamples/IOExamples/fileEx.c stdin and stdout are also type FILE* stderr corresponds to standard error output (different from stdout) – different window on screen

10 Example #include<stdio.h> int main() { FILE* fp = fopen("example.txt", "r"); if(fp == NULL) { printf("Can't open %s\n", "example.txt"); exit(1); // failure } // Read from the file... fclose(fp); return 0;

11 File Path In Windows, specify path with \\ or / instead of \
Use the call fopen("c:\\project\\test1.dat", "r"); or fopen("c:/project/test1.dat", "r");

12 File Input reads one character from stream
int getc(FILE* fp) reads one character from stream returns that character or EOF (error or end of file) Note: getchar uses stdin to read a character char *fgets(char *line, int maxlen, FILE* fp) reads single line up to maxlen-1 characters from input, including (possibly) line break '\n' returns a pointer to character array line returns NULL if end of stream fgets stops reading when it reaches \n, but includes \n in the string Returns line if no error. NULL is returned if no chars read and end of file encountered. CExamples/IOExamples/fileEx2.c. (getc example)

13 File Input int fscanf(FILE* fp, char format[], var-address-list) like scanf and sscanf except items read from input stream fp Cexamples/IOExample/fscanfEx.c

14 File Output int putc(int c, FILE* fp)
writes character c to output stream returns c (or EOF on error) Note: putchar is equivalent to putc(c, stdout) int fputs(char line[], FILE* fp) writes line to output stream returns 0 on success, EOF otherwise int fprintf(FILE *fp, char format[], var-list) Similar to printf, sprintf CExamples/IOExamples/fprintfEx.c

15 Example /* Read line from keyboard & write to file */ int main() { char fileName[80]; char str[80]; FILE *fp; printf("Enter file name: "); scanf("%79s", fileName); // remember: \n still in input stream getchar(); // grab newline character printf("Filename: %s\n", fileName); //fgets(fileName, 80, stdin); // Alternative: remember that \n // included in string though fp = fopen(fileName, "w"); if(fp == NULL) { printf("File %s failed to open\n", fileName); exit(EXIT_FAILURE); } printf("Enter a string: "); fgets(str, 80, stdin); fputs(str, fp); fclose(fp); CExamples/IOExamples/fileEx.c fgets: reads characters from stream and stores them in string str until 79 characters have been read or newline or EOF reached Newline makes fgets stop reading but is also included in string str Note: exit() is in stdlib.h. Terminates calling procedure immediately, returning status EXIT_FAILURE is macro – indicates unsuccessful termination

16 Exercise Write a program that reads in all the lines from a file, and writes each line to the console, inserting the line number at the beginning of the line.


Download ppt "Plan for the Day: I/O (beyond scanf and printf)"

Similar presentations


Ads by Google