CSE 2421: Systems I Low-Level Programming and Computer Organization Input / Output Functions Presentation G Read/Study: Reek Chapter 15 Gojko Babić 10-03-2018 Input and Output Functions The stdio.h contain declarations for I/O functions. There are two types of I/O stream and associated functions: Text streams: text lines of up to at least 254 characters, terminated by a newline (Linux); I/O functions take task of translating between the external and internal forms. Binary stream: written to the file or device as the program wrote them and delivered to the program exactly as they were read from the file or device; we will not consider those. One of declarations in stdio.h is for the FILE structure: a FILE is a data structure to access a stream, If a several different streams are active at a time, each will have its own FILE structure associated with it. Run time C environment provides three standard streams: stdin (a keyboard), stdout (a display) and stderr (a display). g. babic Presentation G 2 1
The printf Functions int fprintf (FILE *stream, char const *format, ) Formats the values of arguments that follow format argument according to the format codes and other characters in the format argument and resulting output goes to stream. Function printf() doesn t have the first argument and prints to the standard output stdout. There is also sprintf() function. Upon successful return, these functions return the number of characters printed. If an output error is encountered, a negative value is returned. Example: int a=1279,z; z = fprintf(stdout, Output:%d hex:%.8x octal:%o\n, a, a, a); printf( Length: %d,z); Displayed Output:1279 hex:000007ff octal:2377 Length: 36 g. babic Presentation G 3 The printf Format Codes Code Argument Meaning d or i int Print an integer value in decimal u unsigned int Print an unsigned integer value in decimal x or X unsigned int Print an unsigned integer value in hexadecimal o unsigned int Print an unsigned integer value in octal e or E double or float Print a floating-point value in exponent notation f double or float Print a floating-point value in conventional notation g or G double or float Print a floating-point value in exp. or conven. notation s char * Print a character string c int Truncated to unsigned char and print as a character p void * Print the value of the pointer Modifier Used with Means the Argument is h d, i, u, x, X, o a (possible unsigned) short integer l d, i, u, x, X, o a (possible unsigned) long integer g. babic Presentation G 4 2
Formatting Width of Numbers on Output %d print as decimal integer %6d print as decimal integer, at least 6 characters wide %f print as floating point, 6 characters after decimal point %6f print as floating point, at least 6 characters wide %.2f print as floating point, 2 characters after decimal point %6.2f print as floating point, at least 6 wide and 2 after decimal point The width of the whole number portion is for decimal integers. The character width for float includes the decimal point position. For additional details of formatting string, integers and floatingpoint values with printf() see Reek Figures 15.1, 15.2, 15.3 and 15.4. printf family of I/O functions are line formatted output functions. g. babic Presentation G 5 C I/O Functions and System Calls C program invoking printf() library call, which in turn calls write() system call. g. babic Presentation G 6 3
Common scanf Format Codes Code Meaning Argument d Read an decimal value and store as signed int * u Read as a decimal value and store as unsigned unsigned * o Read as a octal value and store as unsigned unsigned * x or X Read as a hex value and store as unsigned unsigned * e or f or g Read a single precision real value float * c Read a single character char * s Read sequence of non-whitespace characters as a character string; the string is nul-terminated array of char Modifier Used with Means the Argument is h d, u, x, X, o a (possible unsigned) short integer l d, u, x, X, o a (possible unsigned) long integer l e, f, g a double precision real value g. babic Presentation G 7 The scanf Functions int fscanf (FILE *stream, char const *format,.) Reads characters from stream, converts them according to the codes given in the format string and stores the results in the locations pointed to by the corresponding pointers in arguments that follow format. Input stops when the end of the format string is reached or input is read that does not match what the format specifies. In either case, the number of input values that were converted is returned as the function value. EOF returned if end of file reached before any value. Function scanf() doesn t have the first argument and reads from stdin. There is also sscanf() function. Example: int a, b, n; float c; n = fscanf(stdin, %d %d %f, &a, &b, &c); Input 4 23466 544.3 Outcome n 3, a 4, b 23466, c 544.3 scanf family of I/O functions are line formatted input functions. g. babic Presentation G 8 4
Moving-Head Disk Mechanism A sector (usually 512 bytes) is a basic unit of transfer (read/write) g. babic Presentation G 9 Overview of File I/O The program has to declare variable of type FILE * for each file that must be simultaneously active. To access any file, it has to be first open by calling the fopen() function. A name of a file to be accessed and how (for reading, writing or both) have to be specified in the fopen() function. Operating system and fopen() verify that the file exists, if you have permission to access in the manner specified, and then the FILE structure is initialized. The file then can be read and/or written using e.g. fprintf() or fscanf() functions. Finally, the stream is closed with the fclose() function. I/O on the standard streams stdin, stdout and stderr is simple because they do not have to be opened or closed. g. babic Presentation G 10 5
Opening File FILE *fopen(char const *name, char const *mode) name is the name of the file that should be open mode indicates how is the file to be used: I/O stream type Read Write Append Read&Write Read&Append text r w a r+ or w+ a+ to open a file for reading ( r or r+ ), the file must already exist. if a file opened for writing ( w or w+) does not exist, it will be created, while if it already exists, it will be truncated to 0 bytes length. if a file opened for appending ( a or a+ ) does not exist, it will be created, while if it already exists, it will not be truncated; in either case, data can be written to the end of the file. if successful, fopen() returns a pointer to the FILE structure (called a file descriptor), otherwise a NULL value is returned. g. babic Presentation G 11 Accessing File Unix/Linux provides a view of a file as a contiguous logical address space without any structure, just as a sequence of bytes. Once a file is opened, a file has the file location indicator associated with it and that is the offset in the file where the next read from the file or write to the file will start. After opening with r, r+, w or w+ the file location indicator has value zero, i.e. it points to the first byte of the file; after opening with a or a+, it points after the last byte of the file. After a file is open, fscanf (or fgets or fgetc) can be used to read from the file, and fprintf (or fputs or fputc) to write into the file. Each read or write starts at a location of the file location indicator and then increments the file location indicator for a number of bytes (including white space characters) read or written. Writing in the middle a file overwrites any existing characters, while writing at its end, enlarges a size of the file. 12 6
Other File I/O Functions int fflush(file *stream); fflush() forces a write of all buffered data for the given output. The open status of the file is unaffected. after writing to the file, fflush() must be called before reading from it; int fclose(file *fp); fclose() closes the file pointed to by fp, thus preventing the associated file from being accessed again, guaranteeing that any data stored in the stream buffer is correctly written to the file, and releases the FILE structure so that it can be used again with another file. fclose() also does tasks of fflush(). void rewind(file *stream); rewind() sets the file location indicator for the stream pointed to by stream to the beginning of the file. int fseek() changes a position of the file location indicator. g. babic Presentation G 13 (fileio) Example with File I/O Functions int main() { FILE *finout; int i1 = 1234, i2 = 987, i3, i; char c1[50], c2[50]; finout = fopen("testfile", "w+"); if (finout == NULL) { printf( Open TestFile failed\n"); return -1; } fprintf(finout, "%d%d", i1,i2); Output: c1=1234987 c1=1234987 c1=2469974 c1=hello c2=1234987 1234987 2469974 Hello rewind(finout); fflush(finout); fscanf(finout, "%d",&i3); fprintf(finout," %d", i3); i3=i3*2; fprintf(finout, " %d %s", i3, "Hello"); rewind(finout); fflush(finout); while(fscanf(finout,"%s", c1)!=eof) printf("\nc1=%s", c1); rewind(finout); i=0; while (fscanf(finout,"%c",&c2[i++])!=eof); c2[i]='\0'; printf("\nc2=%s", c2); fclose(finout); return; } g. babic 14 7
Redirecting stdin and stdout It is possible to redirect stdout to a file instead of the screen/monitor : Example: %lab2c > OutFile > makes that output from the program lab2c will be redirected to the file OutFile if OutFile already exists error Example: % lab2c >! OutFile! overwrites if the file OutFile already exists. It is possible to redirect stdin from a file instead of the keyboard Example: %lab2c < InFile < makes that the program gets input from the file InFile. Redirecting stdin&stdout example: % lab2c < lnfile >! OutFile1 Redirecting is a support from the operating system Linux. g. babic Presentation G 15 Character I/O Functions (included for completeness) int fgetc (FILE *stream); Reads the next character from stream (as unsigned char), returns it as the value of the function (whatever it is) as int. EOF returned, if end of file reached or error. Why is int returned instead of char? Function getchar() has empty argument list and reads from stdin. There is also getc() function identical to fgetc(). int fputc (int character, FILE *stream); Truncates the integer variable to an unsigned character and writes it to stream. EOF returned if an error occurred while writing, otherwise the character written returned as int. Function putchar() does not have the secon parameter and writes to stdout. There is also putc() function identical to fputc(). int ungetc (int character, FILE *stream); Returns a character previously read back to stream g. babic Presentation G 16 8
Unformatted Line I/O Functions (for completeness) char *fgets (char *buffer, int buffer_size, FILE *stream); Reads characters from stream and copies them into buffer. Reading stops after a newline character has been read and stored in buffer. It also stops after buffer_size-1 characters has been stored in buffer, and in this case the next fgets() will get the next character from stream. In either case, a nul byte is appended to the end of whatever is stored in the buffer. If end of file is reached before any character have been read, buffer is unchanged and fgets returns a NULL pointer, otherwise the pointer to buffer is returned. Also: gets() int *fputs (char const *buffer, FILE *stream); buffer must contain a string, i.e. expected to be nul character terminated, and its characters are written to stream. if an error occurred while writing, fputs() returns EOF, otherwise it returns a non-negative value. Also: puts() g. babic Presentation G 17 9