90 likes | 303 Views
System IO. CAS CS210 Ying Ye. Boston University. Files. In Linux, all I/O devices are modeled as files All input and output is performed by reading and writing the appropriate files When a file is opened, system returns a file descriptor , which is used to access the file. Standard I/O.
E N D
System IO CAS CS210 Ying Ye Boston University
Files • In Linux, all I/O devices are modeled as files • All input and output is performed by reading and writing the appropriate files • When a file is opened, system returns a file descriptor, which is used to access the file
Standard I/O • getchar(), putchar(), scanf(), printf()...... • When each process is created, three files are opened: • standard input • standard output • standard error
Standard I/O • int getchar(void): read a character from standard input stream, return it as int • int putchar(int c): write the character c to standard output stream • Usage: char a = getchar(); putchar(a); • Practice: http://cs-people.bu.edu/yingy/input.c http://cs-people.bu.edu/yingy/output.c
Standard I/O input.c: char string[6]; int i; for(i = 0; i < 5; i++) string[i] = getchar(); string[i] = '\0' printf(string); output.c: int len = 0; while(string[len] != '\0'){ len++; } int i; for(i = 0; i < len; i++) putchar(string[i]);
File I/O • File object in Standard C library: FILE it contains the current position indicator in the file • Open file: FILE *fopen(char *name, char *mode); mode: "r": read only "r+": read and write e.g. FILE *fp = fopen("file_name", "r+");
File I/O • Read: int getc(FILE *fp); returns a character from the current position in file, current position moves one byte forward e.g. char c = getc(fp); • Write: int putc(int c, FILE *fp); writes a character c to file fp, current position moves one byte forward e.g. char c = 'a'; putc(c, fp);
File I/O • Close file: int fclose(FILE *fp); • Download: http://cs-people.bu.edu/yingy/file.c • First, create an empty file: vim testfile, then save and quit it • Open testfile after you run your program
File I/O fp = fopen("testfile", "r+"); fprintf(fp, string); //doesn't put terminator to testfile buffer = (char *)malloc(29 * sizeof(char)); fseek(fp, 0, SEEK_SET); int i = 0; while(i < 28) buffer[i++] = getc(fp); buffer[i] = '\0'; fclose(fp);