Вы находитесь на странице: 1из 18

Chapter 6: Input/output

EE3490E: Programming T1 2012/2013 Dr. o Trung Kin 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
EE3490E: Programming T1 2012/2013 Dr. o Trung Kin 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 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, ...);
EE3490E: Programming T1 2012/2013 Dr. o Trung Kin Hanoi Univ. of Science and Technology

Read from stdin

Input/output with files

File type:

typedef struct { } FILE; FILE structure has a field that store currently read/write position of that file, which is called file pointer FILE* fopen(const char* fname, const char* mode);
mode "r" "w" Description Permit only read access Permit only write, erase old file content or create a new file if not existing Permit only write, set the file pointer to the end of file, or create a new file if not existing Text file read/write mode mode "r+" "w+" Description Permit read and write access Permit read and write, erase old file content or create a new file if not existing Permit read and write, set the file pointer to the end of file, or create a new file if not existing Binary file read/write mode

Steps to manipulate with files: Open/create file Read/write data Close

Open files:

"a"

"a+"

"t"
4

"b"

EE3490E: Programming T1 2012/2013 Dr. o Trung Kin 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 T1 2012/2013 Dr. o Trung Kin 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 _SH_DENYNO _SH_DENYRD _SH_DENYWR Definition Permit read and write access Deny read access to the file Deny write access to the file

_SH_DENYRW

Deny read and write access to the file

Attn: Only available in MS Visual C


EE3490E: Programming T1 2012/2013 Dr. o Trung Kin 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
EE3490E: Programming T1 2012/2013 Dr. o Trung Kin 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
int feof(FILE* file);

Test for end-of-file condition:

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);


EE3490E: Programming T1 2012/2013 Dr. o Trung Kin Hanoi Univ. of Science and Technology

Other file read/write functions

Close file:

int fclose(FILE* file); void rewind(FILE* file); int fseek(FILE* file, long offs, int org); org = SEEK_CUR: initial position is current position org = SEEK_END: initial position is end of file org = SEEK_SET: initial position is beginning of file

Move file pointer:


Query current position:

long ftell(FILE* file); int remove(const char* path); int rename(const char* old, const char* new);
EE3490E: Programming T1 2012/2013 Dr. o Trung Kin Hanoi Univ. of Science and Technology

Delete file:

Rename and move file:

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 T1 2012/2013 Dr. o Trung Kin 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 nh hng li u vo/ra chun:
Command Description Redirect stdout to file, create new file or erase old file if existing Redirect stderr to file, create new file or erase old file if existing Redirect stdout to file, append to end of file Redirect stderr to file, append to end of file Redirect stdin to file Redirect stdout of command1 to stdin of command2
EE3490E: Programming T1 2012/2013 Dr. o Trung Kin Hanoi Univ. of Science and Technology

command > file command 1> file command 2> file command >> file command 1>> file command 2>> file command < file command1 | command2
11

stdin, stdout, stderr (cont.)

Some special files


File name Description File name Description

&0
&1 &2 aux

stdin
stdout stderr AUX port

nul
prn, lpt1-9 con com1-9

Discard all data


Printer Console 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 T1 2012/2013 Dr. o Trung Kin Hanoi Univ. of Science and Technology

Read/write on memory buffer

Write:

sprintf(char* buffer, const char* format, ...); sscanf(const char* buffer, const char* format, ...);

Read:

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"
EE3490E: Programming T1 2012/2013 Dr. o Trung Kin Hanoi Univ. of Science and Technology

13

Safe input/output

14

EE3490E: Programming T1 2012/2013 Dr. o Trung Kin 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
EE3490E: Programming T1 2012/2013 Dr. o Trung Kin Hanoi Univ. of Science and Technology

15

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, strcat_s(char* dest, _strlwr_s(char* str, _strupr_s(char* str, int int int int size, const char* src); size, const char* src); size); size);

16

EE3490E: Programming T1 2012/2013 Dr. o Trung Kin 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 T1 2012/2013 Dr. o Trung Kin 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 return the size of a file given from parameter

18

EE3490E: Programming T1 2012/2013 Dr. o Trung Kin Hanoi Univ. of Science and Technology

Вам также может понравиться