[PDF] [PDF] Input/Output and Standard C Library

Line oriented functions – puts(), gets() and variants fputs(), fgets() □ Text files can The program (user) needs to have sufficient rights for reading from the file



Previous PDF Next PDF





[PDF] Input/Output

read lines from stdin fgets, feof write chars to file fopen lines c Read lines from file To read a text file one line at a time, assuming it has short lines, use this



[PDF] C library function - fgets() - Tutorialspoint

The C library function char *fgetschar ∗ str, intn, FILE ∗ stream reads a line newline character is read, or the end-of-file is reached, whichever comes first



[PDF] fgets() - Assembly Language

I/O commands are not included as part of the C language Instead, they are part of the Reads a formatted string fopen Open/create a file for I/O fprintf Writes a formatted string to a file may need to read another line before it can find that 



[PDF] fopen - Quiz on Ch9

The stream/file is a sequence of lines – Each line Data is read and written as a continuous stream The newline character '\n' that C uses internally is not to



[PDF] Lecture 9 - data files

Lecture 9 - data files Input and Stream of characters is built of strings of lines; each line is ended with the new line character Reading one character from the standard input: A file may be opened by means of the library function fopen



[PDF] Lecture 02 C Strings and File IO

To open a file for reading we simply use the fopen function defined in stdio This indicates that the file with the filename(a string) is open for read only We can



[PDF] Programming in C - WUSTL Math

should be non-trivial, 200 lines or more Original content Before a file can be used, it must be opened using the function fopen, its syntax is fp = fopen( name 



[PDF] Input/Output and Standard C Library

Line oriented functions – puts(), gets() and variants fputs(), fgets() □ Text files can The program (user) needs to have sufficient rights for reading from the file



[PDF] Interactive Input in C

A standard task in C programming is to get interactive input from the user; that is, to read in a number or a string typed at the keyboard 1 fgets reads in a line terminated by an end-of-line character (e g , “enter”); file handle for input file */



[PDF] Unformatted and binary input and output Physics and Astronomy

Sometimes we just want to read in a whole line of text into a character array, referred to as The fgets() function reads a line from a file without interpreting it If we want to read in a char variable, let's call it c, we might write: char c; int i;

[PDF] c read file line by line getline

[PDF] c read file line by line into array

[PDF] c read file line by line into char array

[PDF] c read file line by line until eof

[PDF] c scientific computing library

[PDF] c sharp interface inheritance

[PDF] c sharp object oriented programming tutorial

[PDF] c sharp scientific computing

[PDF] c sharp tutorial pdf download

[PDF] c spire account pin

[PDF] c spire bring your own phone

[PDF] c spire customer service

[PDF] c spire customer service fiber

[PDF] c spire customer service hours

[PDF] c spire hattiesburg

Input/Output and Standard C Library

Jan Faigl

Department of Computer Science

Faculty of Electrical Engineering

Czech Technical University in Prague

Lecture 06

BE5B99CPL - C Programming Language

Jan Faigl, 2017

BE5B99CPL - Lecture 06: I/O and Standa rdLib rary

1 / 50

Overview of the Lecture

Part 1 - Input and Output

File Operations

Character Oriented I/O

Text Files

Block Oriented I/O

Non-Blocking I/O

Terminal I/OK. N. King: chapters 22

Part 2 - Selected Standard Libraries

Standard library - Selected Functions

Error HandlingK. N. King: chapters 21, 23, 24, 26, and 27

Jan Faigl, 2017

BE5B99CPL - Lecture 06: I/O and Standa rdLib rary

2 / 50

File OperationsCha racterOriented I/O T extFiles Blo ckOriented I/O Non-Blo ckingI/O T erminalI /O

Part I

Input and Output

Jan Faigl, 2017

BE5B99CPL - Lecture 06: I/O and Standa rdLib rary

3 / 50

File OperationsCha racterOriented I/O T extFiles Blo ckOriented I/O Non-Blo ckingI/O T erminalI /O Text vs Binary FilesThere is not significant difference between text and binary files from the machine processing perspectiveText files are oriented to be a human readable In text files, bytes represent charactersThe content is usually organized into lines

Different markers for theend-of-lineare used (1 or 2 bytes)There can be a special marker for theend-of-file(Ctrl-Z)

It is from CP/M and later used in DOS. It is not widely used in Unix like systems.For parsing text files, we can use

Character oriented functions -putchar(),getchar(),putc(),getc()Functions for formatted i/o -printf()andscanf()as shortcuts for the

fprintf()andfscanf()with thestdinandstdoutstreamsLine oriented functions -puts(),gets()and variantsfputs(),fgets()Text files can be considered as a sequence of bytes

Numeric values as text need to be parsed and formatted in writing Numbers in binary files may deal with byte ordering

E.g., ARM vs x86

Jan Faigl, 2017

BE5B99CPL - Lecture 06: I/O and Standa rdLib rary

4 / 50

File OperationsCha racterOriented I/O T extFiles Blo ckOriented I/O Non-Blo ckingI/O T erminalI /O

File openFunctions for input/output are defined in the standard libraryThe file access is through using a pointer to a file (stream)FILE*File can be opened usingfopen()

FILE*fopen(constchar * restrictpath,const char * restrictmode); Notice, therestrictkeywordOperations with the files are

Stream oriented - sequential reading/writing

Thecurrent p ositionin the file is lik ea cursorAt the opening the file, the cursor is set to the beginning of the file

The mode of the file operations is specified in themodeparameter"r"- reading from the file

The program (user) needs to have sufficient rights for reading from the file."w"- writing to the file

A new file is created if it does not exists; otherwise the content of the

file is cleared."a"- append to the file - the cursor is set to the end of the fileThe modes can be combined, e.g.,"r+"open the file for reading

and writingSeeman fopen

Jan Faigl, 2017

BE5B99CPL - Lecture 06: I/O and Standa rdLib rary

6 / 50

File OperationsCha racterOriented I/O T extFiles Blo ckOriented I/O Non-Blo ckingI/O T erminalI /O fopen(),fclose(), andfeof()Test the file has been opened

1char*fname = " file.txt";

2

3if((f = f open(fname," r")) == NULL) {

4fprintf(stderr," Error:open f ile"% s"\n", fname);

5}Close file -int fclose(FILE *stream);

1if(fclose(f) == EOF) {

2fprintf(stderr," Error:close f ile"% s"\n", fname);

3}Test of reaching the end-of-file (EOF) -int feof(FILE *stream);

Jan Faigl, 2017

BE5B99CPL - Lecture 06: I/O and Standa rdLib rary

7 / 50

File OperationsCha racterOriented I/O T extFiles Blo ckOriented I/O Non-Blo ckingI/O T erminalI /O File PositioningEvery stream has the cursor, i.e., an associated file position

The position can be set usingoffsetrelatively towhenceint fseek(FILE *stream, long offset, int whence);

wherewhenceSEEK_SET- set the position from the beginning of fileSEEK_CUR- relatively to the current file positionSEEK_END- relatively to the end of file

If the position is successfully set,fseek()returns 0void rewind(FILE *stream);sets the position to the beginning

of fileThe position can be stored and set by the functions int fgetpos(FILE * restrict stream, fpos_t * restrict pos); int fsetpos(FILE *stream, const fpos_t *pos);

Seeman fseek,man rewind, etc

Jan Faigl, 2017

BE5B99CPL - Lecture 06: I/O and Standa rdLib rary

8 / 50

File OperationsCha racterOriented I/O T extFiles Blo ckOriented I/O Non-Blo ckingI/O T erminalI /O File Stream ModesModes in thefopen()can be combined

FILE*fopen(constchar * restrictpath,const char * restrictmode);"r"open for reading"w"Open for writing (file is created if it does not exist)"a"open for appending (set cursor to the end of file or create a

new file if it does not exists)"r+"open for reading and writing (starts at beginning)"w+"open for reading and writing (truncate if file exists)"a+"open for reading and writing (append if file exists)There are restrictions for the combined modes with"+"We cannot switch from reading to writing without calling a file-

positioning function or reaching the end of fileWe cannot switch from writing to reading without callingfflush()

or calling a file-positioning function.

Jan Faigl, 2017

BE5B99CPL - Lecture 06: I/O and Standa rdLib rary

9 / 50

File OperationsCha racterOriented I/O T extFiles Blo ckOriented I/O Non-Blo ckingI/O T erminalI /O Temporary FilesFILE* tmpfile(void);- creates a temporary file that exists until it is closed or the program existschar* tmpnam(char *s);- generates a name for a temporary fileIfsisNULL, it creates a name and store it in a static variable and return a pointer to itOtherwise it copies the string into the provided character array (s) and returns the pointer to the first character of the array

Jan Faigl, 2017

BE5B99CPL - Lecture 06: I/O and Standa rdLib rary

10 / 50

File OperationsCha racterOriented I/O T extFiles Blo ckOriented I/O Non-Blo ckingI/O T erminalI /O

File Bufferingint fflush(FILE *stream);- flushes buffer for the givenstreamfflush(NULL);- flushes all buffers (all output streams)Change the buffering mode, size, and location of the buffer

int setvbuf(FILE * restrict stream, char * restrict buf, int mode, size_t size);

Themodecan be one of the following macros

_IOFBF- full buffering. Data are read from the stream when buffer is empty and written to the stream when it is full _IOLBF- line buffering. Data are read or written from/to the stream one line at a time _IONBF- no buffer. Direct reading and writing without buffer define

BUFFER _SIZE512

char buffer[BU FFER_SIZE];

setvbuf(stream, buffer, _IOFBF, BUFFER_SIZE);void setbuf(FILE * restrict stream, char * restrict buf);

- similar tosetvbuf()but with default mode

Jan Faigl, 2017

BE5B99CPL - Lecture 06: I/O and Standa rdLib rary

11 / 50

File OperationsCha racterOriented I/O T extFiles Blo ckOriented I/O Non-Blo ckingI/O T erminalI /O

Detecting End-of-File and Error ConditionsThree possible errors can occur during reading data (e.g.,fscanf)End-of-file- w ereach the end of file

Or, the stream is closed, e.g.,stdinRead error- the read function is unable to read data from the stream

Matching failure- the read data do esnot match the requeste dfo rmat

Each stream (FILE*) has two indicators:error indicator- indicates that a read or write error occursend-of-file indicator- is set when the end of file is reachedThe indicators can be read (tested if the indicator is set or not) and

clear the error and eof indicatorsint ferror(FILE *stream); void clearerr(FILE *stream); int feof(FILE *stream);

Jan Faigl, 2017

BE5B99CPL - Lecture 06: I/O and Standa rdLib rary

12 / 50

File OperationsCha racterOriented I/O T extFiles Blo ckOriented I/O Non-Blo ckingI/O T erminalI /O

Reading and Writing Single ByteBasic function for reading fromstdinandstdoutaregetchar()andputchar()Both function returnintvalue, to indicate an error (EOF)The written and read values are converted tounsigned charThe variants of the function for the specific stream are

int getc(FILE *stream);and

int putc(int c, FILE *stream);getchar()is equivalent togetc(stdin)putchar()is equivalent toputc()with thestdoutstreamReading byte-by-byte (unsigned char) can be also used to read

binary data, e.g., to construct 4 bytes lengthintfrom the four byte (char) values

Jan Faigl, 2017

BE5B99CPL - Lecture 06: I/O and Standa rdLib rary

14 / 50

File OperationsCha racterOriented I/O T extFiles Blo ckOriented I/O Non-Blo ckingI/O T erminalI /O Example - Copy usinggetc()andputc()1/2Simple copy program based on reading bytes fromstdinand writing them tostdout

1intc;

2intbytes = 0;

3while((c = getc(stdin)) != EOF) {

4if(putc(c, stdout) == EOF) {

5fprintf(stderr," Errori nputc ");

6break;

7}

8bytes += 1;

9} lec06/copy-getc_putc.c

Jan Faigl, 2017

BE5B99CPL - Lecture 06: I/O and Standa rdLib rary

15 / 50

File OperationsCha racterOriented I/O T extFiles Blo ckOriented I/O Non-Blo ckingI/O T erminalI /O

Example - Copy usinggetc()andputc()2/2We can count the number of bytes and need time to copy the bytes

1#include

2...3

4structtimeva lt1, t2;

5gettimeofday(&t1, NULL);

6

7...// cop ythe stdin -> stdout

8

9gettimeofday(&t2, NULL);

10doubledt = t2.tv_sec - t1.tv_sec + ((t2.tv_usec - t1.

tv_usec) / 1000000.0);

11doublemb = bytes / (1024 * 1024);

12fprintf(stderr," %.2lfMB /sec\n", mb / dt);lec06/copy-getc_putc.cExample of creating random file and using the program

clang -O2 copy-getc_putc.c dd bs=512m count=1 if =/dev/random of=/tmp/rand1.dat1+0 recordsin 1+0 records out

536870912 bytes transferred

in

7.89722 7secs (67982205 bytes/s ec)

./a.out < /tmp/rand1.dat >/tmp/rand2.dat

326.10 MB/sec

Jan Faigl, 2017

BE5B99CPL - Lecture 06: I/O and Standa rdLib rary

16 / 50

File OperationsCha racterOriented I/O T extFiles Blo ckOriented I/O Non-Blo ckingI/O T erminalI /O Line Oriented I/OA whole (text) line get to be read by char* gets(char *str);

char* fgets(char * restrict str, int size, FILE * restrict stream);gets()cannot be used securely due to lack of bounds checkingA line can be written byfputs()anputs()puts()write the given string and anewline cha racterto the

stdoutstreamputs()andfputs()return a non-negative integer on success and

EOFon error

Seeman fgets,man fputs

Jan Faigl, 2017

BE5B99CPL - Lecture 06: I/O and Standa rdLib rary

18 / 50

File OperationsCha racterOriented I/O T extFiles Blo ckOriented I/O Non-Blo ckingI/O T erminalI /O Formatted I/O -fscanf()int fscanf(FILE *file, const char *format, ...); It return number of read items, e.g., for the input record 1 13.4The statement int r = f scanf(f, s d lf n , str, &i, &d);sets (in the case of success) the variable r to the value 3 r == 3For reading strings, it is necessary to respect the size of the allocated memory , e.g., by using the limited length of the read string char str[10]; int r = fs canf(f, %9 s d lf n , str, &i, &d); lec06/file_scanf.c

Jan Faigl, 2017

BE5B99CPL - Lecture 06: I/O and Standa rdLib rary

19 / 50

File OperationsCha racterOriented I/O T extFiles Blo ckOriented I/O Non-Blo ckingI/O T erminalI /O Formatted I/O -fprintf()int fprintf(FILE *file, const *format, ...); int main( int a rgc, char *argv[]) {char*fname = argc > 1 ? argv[ 1]: " out.txt";FILE *f;if((f = fopen(fname, " w")) == NULL) {

fprintf(stderr," Error:O penfile "% s"\n", fname);return-1; }fprintf(f," Programarguments argc :% d\n", argc);

for int i = 0; i < argc; + +i){ fprintf(f, argv d s n , i, argv[i]); }if(fclose(f) == EOF) { fprintf(stderr," Error:C losefile "% s"\n", fname);return-1; }return0; }lec06/file_printf.c

Jan Faigl, 2017

BE5B99CPL - Lecture 06: I/O and Standa rdLib rary

20 / 50

File OperationsCha racterOriented I/O T extFiles Blo ckOriented I/O Non-Blo ckingI/O T erminalI /O Block Read/WriteWe can usefread()andfwrite()to read/write a block of data size_t fread( void restrict ptr, size_t size, size_t nmemb,

FILE *

restrict stream); size_t fwrite( const void restrict ptr, size_t size, size_t nmemb,

FILE *

restrict stream); Useconstto indicate (ptr) is used only for reading

Jan Faigl, 2017

BE5B99CPL - Lecture 06: I/O and Standa rdLib rary

22 / 50

File OperationsCha racterOriented I/O T extFiles Blo ckOriented I/O Non-Blo ckingI/O T erminalI /O Block Read/Write - Example 1/4Program to read/write a given (as#define BSIZE) number of

intvalues using#define BUFSIZElength bufferWriting is enabled by the optional program argument-wFile for reading/writing is a mandatory program argument

1#include

2#include

3#include

4#include

5#include

6#include

7

8#include

9

10#ifndefBUFSIZE

11#defineBUFSIZE 32768

12#endif

13

14#ifndefBSIZE

15#defineBSIZE 4098

16#endif17intmain( intargc, char *argv[])

18{

19intc = 0;

20_Bool read = true;

21constchar *fnam e= NULL;

22FILE *file;

23constchar *mode = " r";

24while(argc-- > 1) {

25fprintf(stderr," DEBUG:argc :% d"% s"\n", argc, argv[argc]);

26if(strcmp(argv[argc], " -w") == 0) {

27fprintf(stderr," DEBUG:enable writting \n");

28read = false;// enable writting

29mode =" w";

30}else {

31fname = argv[argc];

32}

33}// end w hilelec06/demo-block_io.c

Jan Faigl, 2017

BE5B99CPL - Lecture 06: I/O and Standa rdLib rary

23 / 50

File OperationsCha racterOriented I/O T extFiles Blo ckOriented I/O Non-Blo ckingI/O T erminalI /O

Block Read/Write - Example 2/4

34file = fopen(fname, mode);

35if(!file) {

36fprintf(stderr," ERROR:Cannot open file "% s",error % d- % s\n", fname, errno, strerror(errno));

37return-1;

38}

39int*data = ( int*)malloc(BSIZE *sizeof (int));

40assert(data);

41structtimeval t1, t2;

42gettimeofday(&t1, NULL);

43if(read) { /* READ FILE */

44fprintf(stderr," INFO:Read from the file "% s"\n", fname);

45c = fread(data,sizeof (int), BSIZE, file);

46if(c != BSI ZE){

47fprintf(stderr," WARN:Read only % iobjects ( int)\n", c);

48}else {

49fprintf(stderr," DEBUG:Read % iobjects ( int)\n", c);

50}

51}else { /* WRITE FILE */

52charbuffer[BUFSIZE];

53if(setvbuf(file, buffer, _IOFBF, BUFSIZE)) { /* SET BUFFER */

54fprintf(stderr," WARN:Cannot set buffer ");

55}

56fprintf(stderr," INFO:Write to the file "% s"\n", fname);

57c = fwrite(data,sizeof (int), BSIZE, file);

58if(c != BSI ZE){

59fprintf(stderr," WARN:Write only % iobjects ( int)\n", c);

60}else {

61fprintf(stderr," DEBUG:Write % iobjects ( int)\n", c);

62}

63fflush(file);

64}

65gettimeofday(&t2, NULL);lec06/demo-block_io.c

Jan Faigl, 2017

BE5B99CPL - Lecture 06: I/O and Standa rdLib rary

24 / 50

File OperationsCha racterOriented I/O T extFiles Blo ckOriented I/O Non-Blo ckingI/O T erminalI /O

Block Read/Write - Example 3/4

66doubledt = t 2.tv_sec- t1.tv_sec + ((t2.tv_us ec- t1.tv_usec) / 1000000.0);

67doublemb = ( sizeof(int) * c)/ (1024 * 1024);

68fprintf(stderr," DEBUG:feof :% iferror :% i\n", feof(file), ferror(file));

69fprintf(stderr," INFO:% s% luMB \n", (read ?" read": " write"),sizeof (int)*BSIZE/(1024 * 1024));

70fprintf(stderr," INFO:%.2 lfMB /sec\n", mb / dt);

71free(data);

72returnEXIT_SUCCESS;

73}DefaultBUFSIZE(32 kB) to write/read 108integer values (480 MB)

clang -DBSIZE=100000000 demo-block_io.c && ./a.out -w a 2>&1 | grep INFO

INFO: Write to the file "a"

INFO: write 381 MB

INFO: 10.78 MB/sec

./a.out a 2>&1 | grep INFO

INFO: Read from the file "a"

INFO: read

381 MB

INFO: 1683.03 MB/secTry to read more elements results infeof(), but not inferror() clang -DBSIZE=200000000 demo-block_io.c && ./a.out a

DEBUG: argc: 1 "a"

INFO: Read from the file "a"

WARN: Read only 100000000 objects (int)

DEBUG: feof: 1 ferror: 0

INFO: read

762 MB

INFO: 1623.18 MB/seclec06/demo-block_io.c

Jan Faigl, 2017

BE5B99CPL - Lecture 06: I/O and Standa rdLib rary

25 / 50

File OperationsCha racterOriented I/O T extFiles Blo ckOriented I/O Non-Blo ckingI/O T erminalI /O Block Read/Write - Example 4/4Increased write bufferBUFSIZE(128 MB) improves writing performance clang -DBSIZE=100000000 -DBUFSIZE=134217728 demo-block_io.c && ./a.out -w aa 2>&1 | grep INFO

INFO: Write to the file "aa"

INFO: write 381 MB

INFO: 325.51 MB/secBut does not improve reading performance, which relies on the standard size of the buffer clang -DBSIZE=100000000 -DBUFSIZE=134217728 demo-block_io.c && ./a.out aa 2>&1 | grep INFO

INFO: Read from the file "aa"

INFO: read

38 1MB

INFO: 1693.39 MB/seclec06/demo-block_io.c

Jan Faigl, 2017

BE5B99CPL - Lecture 06: I/O and Standa rdLib rary

26 / 50

File OperationsCha racterOriented I/O T extFiles Blo ckOriented I/O Non-Blo ckingI/O T erminalI /O

Blocking and Non-Blocking I/O OperationsUsually I/O operations are considered asblocking requestedSystem call does not return control to the application until the re-

quested I/O is completedIt is motivated that we need all the requested data and I/O opera- tions are usually slower than the other parts of the program.

We have to wait for the data anywayIt is also calledsynchronousprogrammingNon-Blockingsystem calls do not wait for unrelated I/O to

complete, and thus do not block the applicationIt is suitable for network programming, multiple clients, graphical

user interface, or when we need to avoid "deadlock" or too long

waiting due to slow or not reliable communicationCall for reading requested data will read (and "return") only data

that are available in the input bufferAsynchronousprogramming withnon-blockingcallsReturn control to the application immediately

Data are transferred to/from buffer "on the background"

Call back, triggering a signal, etc.

Jan Faigl, 2017

BE5B99CPL - Lecture 06: I/O and Standa rdLib rary

28 / 50

File OperationsCha racterOriented I/O T extFiles Blo ckOriented I/O Non-Blo ckingI/O T erminalI /O Non-Blocking I/O Operations - ExampleSetting the file stream (file descriptor) to theO_NONBLOCKmode Also for socket descriptorFor reading from regular files it does not too much sense to use non-blocking operationsReading from block devices such as serial port, e.g.,/dev/ttyS10 may be more suitableWe can setO_NONBLOCKflag for a file descriptor usingfcntl() include POSIX open fil eby the open() syste mcall that return a file descriptor int fd = open(quotesdbs_dbs6.pdfusesText_11