Page 143 - 6437
P. 143

fp = fopen("/tmp/test.txt", "r");

                                fscanf(fp, "%s", buff);
                                printf("1 : %s\n", buff );


                                fgets(buff, 255, (FILE*)fp);

                                printf("2: %s\n", buff );


                                fgets(buff, 255, (FILE*)fp);
                                printf("3: %s\n", buff );

                                fclose(fp);


                            }

                          When the above code is compiled and executed, it reads the file created in the previous
                   section and produces the following result:


                 1 : This
                 2: is testing for fprintf...


                 3: This is testing for fputs...

                          Let's see a little more in detail about what happened here. First, fscanf() reads just  This
                   because  after  that,  it   encountered   a   space,   second   call   is for fgets() which reads the
                   remaining line till it encountered end of line. Finally, the last call fgets() reads the second line
                   completely.

                          Binary I/O Functions
                 size_t fread(void *ptr, size_t size_of_elements,

                                 size_t number_of_elements, FILE *a_file);
                 size_t fwrite(const void *ptr, size_t size_of_elements,

                                 size_t number_of_elements, FILE *a_file);

                          There are two functions that can be used for binary input and output:

                          Both of these functions should be used to read or write blocks of memories - usually
                   arrays or structures.











                                                                                                     147
   138   139   140   141   142   143   144