Lecture 6: Input/Output
1 EE3490E: Programming – S1 2017/2018
Dr. Đào Trung Kiên – Hanoi Univ. of Science and Technology
Overview
Programmers usually need to work with input, output
devices like screen, keyboard, files, printer,…
For each program, there are:
A standard output stdout: console by default, can be
considered as a virtual write-only file, and can be
redefined as a file on disk, or printer,…
A standard error output stderr: like stdout but usually used
to export error or warning messages when program
encounters
A standard input stdin: keyboard by default, can be
considered as a virtual read-only file, and can be
redefined as a file on disk
2 EE3490E: Programming – S1 2017/2018
Dr. Đào Trung Kiên – Hanoi Univ. of Science and Technology
Start off
Write to stdout
Write a character:
int putchar(int c);
Write a string and append a newline character ('\n'):
int puts(const char* s);
Write formatted data:
int printf(const char* format, ...);
Read from stdin
Read a character:
int getchar();
Read characters as a string until a newline character:
char* gets(char* s);
Read formatted data:
int scanf(const char* format, ...);
3 EE3490E: Programming – S1 2017/2018
Dr. Đào Trung Kiên – Hanoi Univ. of Science and Technology
Input/output with files
File type:
typedef struct { … } FILE;
Steps to manipulate with files: Open/create file Read/write data Close
FILE structure has a field that store currently read/write position of that file,
which is called file pointer
Open files:
FILE* fopen(const char* fname, const char* mode);
mode Description mode Description
"r" Permit only read access "r+" Permit read and write access
"w" Permit only write, erase old file "w+" Permit read and write, erase
content or create a new file if old file content or create a new
not existing file if not existing
"a" Permit only write, set the file "a+" Permit read and write, set the
pointer to the end of file, or file pointer to the end of file, or
create a new file if not existing create a new file if not existing
"t" Text file read/write mode "b" Binary file read/write mode
4 EE3490E: Programming – S1 2017/2018
Dr. Đào Trung Kiên – Hanoi Univ. of Science and Technology
Remarks on opening files
NULL returned when opening fails need to check
return value of fopen() to see if opening
succeeded
Failure causes:
Open an non-existing file
Permission denied
File in used by another program with re-open restriction
Too many files being opened (OS has limit on number of
concurrent opened files)
Files opened by fopen() can be re-opened by
another programs
5 EE3490E: Programming – S1 2017/2018
Dr. Đào Trung Kiên – Hanoi Univ. of Science and Technology
Open files with re-open restriction
A program might desire to restrict other programs from
intervention to its opened files use _fsopen()
FILE* _fsopen(const char* fname, const char*
mode, int shflag);
shflag: restriction flag (or share flag)
#include <share.h>
shflag value Definition
_SH_DENYNO Permit read and write access
_SH_DENYRD Deny read access to the file
_SH_DENYWR Deny write access to the file
_SH_DENYRW Deny read and write access to the file
Attn: Only available in MS Visual C
6 EE3490E: Programming – S1 2017/2018
Dr. Đào Trung Kiên – Hanoi Univ. of Science and Technology
Writing to files
Text and binary files
Text files: operations including processing some special characters
(new line, space, tab,…) suitable for human readable text
Binary files: no special characters processing suitable for
binary structured data
Write textual data:
int fputc(int c, FILE* file);
int fputs(const char* s, FILE* file);
int fprintf(FILE* file, const char* format, ...);
Similar to putchar(), puts(), printf()
Write binary data:
int fwrite(const void* buf, int size, int count, FILE*
file);
Write an array of count elements where each one are size-byte length
7 EE3490E: Programming – S1 2017/2018
Dr. Đào Trung Kiên – Hanoi Univ. of Science and Technology
Read from files
Read textual data:
int fgetc(FILE* file);
int fgets(char* s, int n, FILE* file);
int fscanf(FILE* file, const char* format, ...);
Similar to getchar(), gets(), scanf(), except returning EOF when
reaching end of file
Read binary data:
int fread(void* buf, int size, int count, FILE* file);
Read an array of count elements where each one are size-byte length
Test for end-of-file condition:
int feof(FILE* file);
As file reading/writing uses buffer, use fflush() to send/clear all
pending data to device, when needing to synchronize reading and
writing states
int fflush(FILE* file);
8 EE3490E: Programming – S1 2017/2018
Dr. Đào Trung Kiên – Hanoi Univ. of Science and Technology
Other file read/write functions
Close file:
int fclose(FILE* file);
Move file pointer:
void rewind(FILE* file);
int fseek(FILE* file, long offs, int org);
org = SEEK_CUR: reference position is current position
org = SEEK_END: reference position is end of file
org = SEEK_SET: reference position is beginning of file
Query current position:
long ftell(FILE* file);
Delete file:
int remove(const char* path);
Rename and move file:
int rename(const char* old, const char* new);
9 EE3490E: Programming – S1 2017/2018
Dr. Đào Trung Kiên – Hanoi Univ. of Science and Technology
Example: copy file
int copy_file(const char* src, const char* dst) {
FILE *fs = NULL, *fd = NULL;
char buf[1024];
int num;
if ((fs = fopen(src,"rb")) == NULL) return -1;
if ((fd = fopen(dst,"wb")) == NULL) { fclose(fs); return -1; }
while(!feof(fs)) {
num = fread(buf, 1, sizeof(buf), fs);
fwrite(buf, 1, num, fd);
}
fclose(fs); fclose(fd);
return 0;
}
10 EE3490E: Programming – S1 2017/2018
Dr. Đào Trung Kiên – Hanoi Univ. of Science and Technology
stdin, stdout, stderr
Standard input/output are actually predefined FILE* printf(…),
scanf(…) functions are equivalent to fprintf(stdout,…) and
fscanf(stdin,…)
Similarly, putchar(), puts(), getchar(), gets() functions also
manipulate stdin and stdout
Redirection of standard input/outputs:
Command Description
command > file Redirect stdout to file, create new file or erase old file if existing
command 1> file
command 2> file Redirect stderr to file, create new file or erase old file if existing
command >> file Redirect stdout to file, append to end of file
command 1>> file
command 2>> file Redirect stderr to file, append to end of file
command < file Redirect stdin to file
command1 | command2 Redirect stdout of command1 to stdin of command2
11 EE3490E: Programming – S1 2017/2018
Dr. Đào Trung Kiên – Hanoi Univ. of Science and Technology
stdin, stdout, stderr (cont.)
Some special files
File name Description File name Description
&0 stdin nul Discard all data
&1 stdout prn, lpt1-9 Printer
&2 stderr con Console
aux AUX port com1-9 COM ports
Ex:
Redirect both stdout and stderr to result.txt file
C:\>dir *.dat >result.txt 2>&1
Redirect stdout to printer and stderr to error.log file
C:\>stuff >prn 2>error.log
Redirect stdin to input.txt file and stdout to output.txt file
C:\>process <input.txt >output.txt
Create pipe (output of one command is input of the other)
C:\>type source.c | more
12 EE3490E: Programming – S1 2017/2018
Dr. Đào Trung Kiên – Hanoi Univ. of Science and Technology
Read/write on memory buffer
Write:
sprintf(char* buffer, const char* format,
...);
Read:
sscanf(const char* buffer, const char*
format, ...);
Usage similar to fprintf() and fscanf() but data are
stored in memory specified by buffer parameter
Ex:
char s[50];
sprintf(s, "sin(pi/3) = %.3f", sin(3.14/3));
Result: value of s will be "sin(pi/3) = 0.866"
13 EE3490E: Programming – S1 2017/2018
Dr. Đào Trung Kiên – Hanoi Univ. of Science and Technology
Safe input/output
14 EE3490E: Programming – S1 2017/2018
Dr. Đào Trung Kiên – Hanoi Univ. of Science and Technology
Buffer overflow error
Happens when program write more data than the size of
buffer
Ex: copy a string of 10 characters into a buffer of 5 bytes
char s[5];
strcpy(s, "0123456789"); /* error */
This error is dangerous as it will cause unpredictable
effects, especially may help user to take ownership of
computer then do anything need to control the length
of input data to fit into memory allocated to variables
Standard C functions do not check buffer overflow error
use extend functions in Visual C from 2005
15 EE3490E: Programming – S1 2017/2018
Dr. Đào Trung Kiên – Hanoi Univ. of Science and Technology
String and memory processing functions
memcpy_s(void* dest, int size, const void* src, int
count);
memmove_s(void* dest, int size, const void* src,
int count);
strcpy_s(char* dest, int size, const char* src);
strcat_s(char* dest, int size, const char* src);
_strlwr_s(char* str, int size);
_strupr_s(char* str, int size);
16 EE3490E: Programming – S1 2017/2018
Dr. Đào Trung Kiên – Hanoi Univ. of Science and Technology
Data reading functions
gets_s(char* str, int size);
scanf_s(const char* format, ...);
Added buffer-size checking parameters
int i;
float f;
char c;
char s[10];
scanf_s("%d %f %c %s", &i, &f, &c, 1, s, 10);
Similar to fscanf_s(), sscanf_s() functions
17 EE3490E: Programming – S1 2017/2018
Dr. Đào Trung Kiên – Hanoi Univ. of Science and Technology
Problems
Write programs to:
1. Convert all characters in a file to upper case
2. Count number of words and number of lines in a file
(words separated by space, tab, newline characters)
3. Append a file to another
4. Print the 10th line of a file
5. Insert a line into a file after the 10th line
6. Input data for struct Student from keyboard, then try to
redirect stdin and stdout to files and see the effects
7. Write a function that returns the size of a file given from
parameter
18 EE3490E: Programming – S1 2017/2018
Dr. Đào Trung Kiên – Hanoi Univ. of Science and Technology