UNIX Advanced Environment Programming (7) Standard IO function library-binary file IO, stream positioning, creating temporary files and memory streams

Source: Internet
Author: User
Tags rewind

?

12 binary io (binary io)

In the previous article we learned about read-only and line-by-read functions.

If we are reading and writing binary files, and want to read and write the entire file content, these two functions can be implemented, but it is obviously cumbersome and many cycles are obviously inefficient.

To address this scenario, the standard IO library provides fread and fwrite functions.

function declaration:

#include <stdio.h>

size_t fread (void *restrict ptr, size_t size, size_t nobj, FILE *restrict FP);

size_t fwrite (const void *restrict ptr, size_t size size_t nobj, FILE *restrict FP);

function usage;

A) Read and write an array.

float DATA[10];

if (write (&data[2], sizeof (float), 4, fp)! = 4)

? ? Err_sys ("fwrite error");

In this example, 4 float data is read from the stream FP into the array below the table from 2 to 5 positions.

b) Read and write a struct

struct {

? ? Short count;

? ? A long? Total

? ? Char? Name[namesize];

} item;

if (fwrite (&item, sizeof (item), 1, fp)! = 1)

? ? Err_sys ("fwrite error");

In this example, the data from the FP is populated into a struct.

?

The above two examples can be considered to read and write an array of structures, the parameter size is the length of the structure, the parameter nobj is the number of elements to read and write in the array.

?

function return value:

The return value of two functions is the number of read and write elements.

For read functions, the return value may be smaller than nobj if an exception is thrown or the end of the file is read. You need to call the function ferror or feof to judge.

For write functions, the return value is smaller than nobj, then there must be an exception thrown.

?

Function Details:

In the example above, we populate a struct with the fwrite function, so if the read/write is not in a system, the memory layout of the struct may not be the same, which is common in scenarios where multi-system interconnection works today. We'll come back to the problem when we talk about sockets, and the real solution is to use the same protocol when reading and writing binary data between different systems.

?

2 locating stream (positioning a stream)

We have three ways to locate the convection:

    • Functions Ftell and Fseek. Stores the current offset position of the file in a long integer variable;
    • Functions Ftello and Fseeko. Stores the current offset of the file in the off_t variable;
    • Functions Fgetpos and Fsetpos. Use the data type to fpos_t the current offset of the record file.

?

Ftell and fseek function declarations:

#include <stdio.h>

Long Ftell (file* fp);??//returns:current FILE Position Indicator if OK, -1l on Error

int fseek (file* fp, long offset, int whence);??? returns:0 if OK,-1 On Error

void Rewind (file* fp);

Function Details:

    • The offset of the binary file is the number of bytes from the beginning of the file to the current position;
    • The Ftell function returns the offset position of the current file;
    • The Fseek function is used to position the file to the specified offset;
    • The parameter whence of the Fseek function is used to set the method for calculating the offset: Seek_set is calculated from the beginning of the file, Seek_cur is calculated from the current offset of the file, and Seek_end is calculated from the end of the file.
    • For some non-UNIX operating systems, the storage format of the stored text file is different, the current file offset cannot be represented by the number of bytes, in which case the parameter whence needs to be set to Seek_set, and offset has only two values that can be used: 0, to rewind the beginning of the text Another available value is the return value of the function Ftell.

?

Ftello and Fseeko function declarations:

#include <stdio.h>

off_t Ftello (file* fp);?? Returns:current file Position Indicator if OK, (off_t)-1 On Error

int Fseeko (file* fp, off_t offset, int whence);?? returns:0 if OK,-1 On Error

Function Details :

    • These two functions are the same as the above Ftell and fseek functions, except that the return value type is not a long and is changed to off_t, which enables the off_t to be represented in a larger range.

?

Fgetpos and Fsetpos function declarations:

#include <stdio.h>

int Fgetpos (file* restrict FP, fpos_t *restrict POS);

int Fsetpos (file* fp, const fpos_t POS);

Function Details:

    • The Fgetpos function saves the current file offset to the parameter pos
    • Fgetpos gets the POS that can be used to set the current file offset to the previous position using Fsetpos.

?

3 format Input Output formatted output function

There are five printf functions that are responsible for formatting the output.

function declaration:

#include <stdio.h>

int printf (const char *restrict format, ...);

int fprintf (FILE *restrict FP, const char *restrict format, ...);

int dprintf (int fd, const char *restrict format,..);

? ? ? All three return:number of characters output if OK, negative value if output error

int sprintf (char *resrict buf, const char *restrict format, ...);

? ? ? Returns:number of characters stored in array if OK, negative value if encoding error

int snprintf (char *restrict buf, size_t N, const char *restrict format, ...);

? ? ? Returns:number of Characters,that would has been stored in array if buffer is large enough, negative value if Encodi ng Error

Function Details:

    • printf output to standard output;
    • fprintf the output to the specified stream;
    • dprintf output to the specified file descriptor;
    • sprintf writes a formatted string to the specified buffer array, automatically at the end with a null terminator, but does not count toward the return value, and sprintf may be out of bounds when buffer is not large enough, so the user is required to ensure that buffer is large enough;
    • snprintf prevents out-of-bounds, adds buffer size parameters to the SPRINGF parameter, all characters that are written out of bounds are ignored, and if the return value is smaller than the buffer length, the output is not truncated.

?

Formatting input functions

function declaration:

#include <stdio.h>

int scanf (const char *restrict format, ...);

int fscanf (FILE *restrict FP, const char *restrict format, ...);

int sscanf (const char *restrict buf, const char *restrict format, ...);

Function Details:

    • The parameter followed by the format parameter contains the address of the variable that holds the read-in string.

For more details on formatting input and output, you can query the UNIX operating system manual.

?

4 getting the file descriptor from the stream

function declaration:

#include <stdio.h>

int Fileno (file* fp);??? Returns:the file descriptor associated with the stream

If we need to invoke the DUP and fcntl, we need to call the function.

?

5 temp file (temporary files)

The standard IO library provides two functions for creating temporary files.

function declaration:

#include <stdio.h>

char* Tempnam (char *ptr);

file* tmpfile (void);

Function Details:

    • The function Tmpnam generates a string that is a valid pathname and does not duplicate any existing files.
    • The function Tmpnam each call produces a different string, knowing the number of Tmp_max.
    • If the function tempnam the parameter PTR is null, the resulting path string exists in the memory static area, and the function return value is a pointer to the path string. If you then call Tempnam with the null parameter again, the previously generated string is overwritten.
    • If the function tempnam the parameter PTR is not NULL, the resulting path string exists within the array that PTR points to, so it is necessary to ensure that the array to which PTR points is at least l_tmpnam in length.
    • The function Tmpfile function creates a temporary binary file (type wb+), the program terminates, or the file is closed, the file is automatically deleted. For UNIX operating systems, generating a binary file has no effect because the kernel does not differentiate between a text file or a binary file.

Example:

Code:

#include "Apue.h"

?

Int

Main (void)

{

? ? char?? name[L_tmpnam], line[maxline];

? ? FILE?? *FP;

?

? ? printf ("%s\n", Tmpnam (NULL));??? / * First TEMP name * /

?

? ? Tmpnam (name);???????????? / * Second TEMP name * /

? ? printf ("%s\n", name);

?

? ? if (fp = tmpfile ()) = = NULL)??? / * Create temp file * /

? ? ? ? Err_sys ("tmpfile error");

?? fputs ("one line of output\ n", FP);? /* Write to temp file */

? ? Rewind (FP);???????????? / * Then read it back * /

? ? if (Fgets (line, sizeof, fp) = = NULL)

? ? ? ? Err_sys ("fgets error");

? ? Fputs (line, stdout);? ? ? ? ? ? ? ? / * Print the line we wrote * /

?

? ? Exit (0);

}

Operation Result:

?

In the system the single UNIX specification defines two other functions for handling temporary files:

function declaration:

char* mkdtemp (char* template);?//Returns:pointer to directory name if OK, NULL on Error

int mkstemp (char* template);??//Returns:file Descriptor if OK,-1 On Error

Function Details:

    • The Mkdtemp function creates a folder with a unique name
    • Mkstemp function creates a generic file with a unique name (regular file)
    • Naming rules for template + six-bit random characters

?

6 Memory Stream (Streams)

Some standard input and output streams do not have a corresponding open hard disk file, all operations are data exchange with in-memory buffer, these streams are called memory streams.

function declaration:

#include <stdio.h>

file* fmemopen (void *restrict buf, size_t size, const char *restrict type);

Returns:stream pointer if OK, NULL on Error

Function Details:

    • The parameter buf specifies the size of the buffer used buffer,size, if only size is specified and BUF is null, Fmemopen allocates memory based on size, and the memory allocated by Fmemopen is automatically freed when the stream is closed;
    • The parameter type controls the functionality of the stream. The possible values and effects are shown in the following table

?

7 Summary

The standard IO function library is used by most UNIX applications.

When using, notice where buffer is used for processing, as this is a confusing place.

?

?

Resources:

"Advanced programming in the UNIX envinronment 3rd"

?

UNIX Advanced Environment Programming (7) Standard IO function library-binary file IO, stream positioning, creating temporary files and memory streams

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.