Plan for the Day IO beyond scanf and printf Standard String and File IO IO in C Input and output facilities provided by standard library lt stdioh gt and not by the language ID: 659118
Download Presentation The PPT/PDF document "Input and Output Topic 7" is the property of its rightful owner. Permission is granted to download and print the materials on this web site for personal, non-commercial use only, and to display it on your personal computer provided you do not modify the materials and that you retain all copyright notices contained in the materials. By downloading content from our website, you accept the terms of this agreement.
Slide1
Input and OutputTopic 7
Plan for the Day:
I/O (beyond
scanf
and
printf
)Slide2
Standard, String and File I/OSlide3
I/O in CInput and output facilities provided by standard library <
stdio.h
>
and not by the language
Text stream consists of series of lines ending with
'\n'Slide4
Standard Input & Outputint
putchar
(
int
c)
prints
char
c
to
stdout
Returns
c,
or
EOF
on error
int
getchar
()
Returns next character from
stdin
Returns
EOF
on errorSlide5
Standard I/O
#include<
stdio.h
>
int
main() {
char c;
printf
("Enter a character: ");
c =
getchar
();
printf
("Character entered was: ");
putchar
(c);
}Slide6
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 inputSlide7
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 errorSlide8
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 = 93.214;sprintf(answer, "%f", number);printf("%c\n", answer[0]);
Output: Name: Sarah, age: 23
Output:
9Slide9
FilesOpen 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 terminatesSlide10
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;
}Slide11
File PathIn Windows, specify path with \\ or / instead of \
Use the call
fopen
("c:\\project\\test1.dat", "r");
or
fopen
("c:/project/test1.dat", "r");Slide12
File Input
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 linereturns NULL if end of streamSlide13
File Input
int
fscanf
(FILE*
fp
, char format[],
var
-address-list)
like
scanf
and
sscanf
except items read from input stream
fpSlide14
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
i
nt
fprintf
(FILE *
fp
, char format[],
var
-list)
Similar to
printf, sprintfSlide15
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
);
}Slide16
ExerciseWrite 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.