Summery of the first homework

Original guidance: 簡單文件IO操作

Additional reference: cppreference

Function

std::fopen<cstdio>

Reference: std::fopen

Header

std::FILE* fopen( const char* filename, const char* mode );

Parameter

  • const char* filename
  • const char* mode(For details, please check the appendix mode)

Return

  • std::FILE*(For details, please check the entry std::FILE)

std::fscanf<cstdio>

Reference: std::fscanf

Header

int fscanf( std::FILE* stream, const char* format, ... );

Parameter

  • std::FILE* stream(For details, please check the entry std::FILE)
  • const char* format(For details, please check the appdendix std::fscanf)
  • ...(received arguments)

Return

  • int
    Number of receiving arguments successfully assigned (which may be 0in case a matching failure occurred before the first receiving argument was assigned), or EOFif input failure occurs before the first receiving argument was assigned.

std::fclose<cstdio>

Reference: std::fclode

Header

int fclose( std::FILE* stream );

Parameter

  • std::FILE* stream

Return

  • int
    0​ on success, EOFotherwise

std::gets<cstdio>

Reference: std::fopen

Warning: You’d better use std::fgetsinstead of std::getsfor its unsecurity of buffer overflowing. For details, please check std::fgets.

Header

char* gets( char* str );

Parameter

  • char* str
    character string to be written

Return

  • char*
    stron success, NULLon failure.

    If the failure has been caused by end of file condition, additionally sets the eofindicator (see std::feof) on stdin.
    If the failure has been caused by some other error, sets the error indicator (see std::ferror) on stdin.

std::fprintf<cstdio>

Reference: std::fprintf

Header

int fprintf( std::FILE* stream, const char* format, ... );

Parameter

  • std::FILE* stream
  • const char* format(For details, please check the appendix std::fprintf)
  • ...
    Arguments specifying data to print.
    If any argument after default conversions is not the type expected by the corresponding conversion specifier, or if there are fewer arguments than required by format, the behavior is undefined.
    If there are more arguments than required by format, the extraneous arguments are evaluated and ignored.

std::fseek<cstdio>

Reference: std::fseek

Header

int fseek( std::FILE* stream, long offset, int origin );

Parameter

  • std::FILE* stream
    (There are some restritions and default settings for the mode of the stream. Please check the entry std::fopen) or the appendix mode for details.)
  • long offset
    number of characters to shift the position relative to origin.
  • int origin
    position to which offset is added. It can have one of the following values:
    SEEK_SET
    SEEK_CUR
    SEEK_END
    Please check the appendix for details.

Return

0​ upon success, nonzero value otherwise.

std::malloc<cstdlib>

Reference: std::malloc

Header

void* malloc( std::size_t size );

Parameter

  • std::size_t size
    number of bytes to allocate

Return

On success, returns the pointer to the beginning of newly allocated memory. To avoid a memory leak, the returned pointer must be deallocated with std::free()or std::realloc().

On failure, returns a null pointer.

std::free<cstdlib>

Header

void free( void* ptr );

Parameter

  • ptr
    pointer to the memory to deallocate

Type

std::FILE

Constant

SEEK_SET

Argument to std::fseekindicating seeking from beginning of the file

SEEK_CUR

Argument to std::fseekindicating seeking from the current file position

SEEK_END

Argument to std::fseekindicating seeking from end of the file

Source Code

#include <cstdio>
#include <cstdlib>
#include <fstream>

int checkyou();
int checkme();
int check();

int checkyou(void) 
{
    FILE *file = std::fopen("you.txt","r");
    if (file) {
        fclose(file);
        return 1;
    } else {
        fclose(file);
        return 0;
    }
}

int checkme(void) 
{
    FILE *file = std::fopen("me.txt","r");
    if (file) {
        fclose(file);
        return 1;
    } else {
        fclose(file);
        return 0;
    }
}

int check() 
{
    char choice;
    std::scanf("%c",&choice);
    if(choice == 'Y') return 1;
    else {if(choice == 'n') return 0;
    else {
        std::printf("Invalid input!\n");
        return EOF;}
    }
}

int main() 
{
    if(!checkyou()) { std::printf("[warning] There is no such a file \"you.txt\", would you like to create a new one?[Y/n]\n");
        if(check()) {
            std::fopen("you.txt","w"); 
            std::printf("A new file \"you.txt\" has been added to the present path.\n");
        }
        else std::printf("The file will not be added.\n");

    } else {
        
       
    if(checkme()) {
        std::printf("The file \"me.txt\" has already existed, would you like to rewrite the file?[Y/n]");
        if(!check()) std::printf("The file \"me.txt\" will not be rewrite.\n"); EOF;
    }      

    FILE *you =std::fopen("you.txt","r");
    // FILE *me =std::fopen("me.txt","w");

    fseek(you, 0, SEEK_END);
    int size = ftell(you);
    fseek(you, 0, SEEK_SET);
    char *buf = (char*)std::malloc(size+1);
    buf[size] = 0;
    fread(buf, 1, size, you);

    // ?? std::snprintf(buf, size, "s",);
    std::ofstream me;
    me.open("me.txt");
    me << buf;

    std::fclose(you);
    // std::fclose(me);
    me.close();
    }
    return 0;
}

Appendix

mode

File access
mode string
Meaning Explanation Action if file
already exists
Action if file
does not exist
"r" read Open a file for reading read from start failure to open
"w" write Create a file for writing destroy contents create new
"a" append Append to a file write to end create new
"r+" read extended Open a file for read/write read from start error
"w+" write extended Create a file for read/write destroy contents create new
"a+" append extended Open a file for read/write write to end create new
File access mode flag "b" can optionally be specified to open a file in binary mode. This flag has no effect on POSIX systems, but on Windows, for example, it disables special handling of '\n' and '\x1A'.
On the append file access modes, data is written to the end of the file regardless of the current position of the file position indicator.
File access mode flag "x" can optionally be appended to "w" or "w+" specifiers. This flag forces the function to fail if the file exists, instead of overwriting it. (C++17)
The behavior is undefined if the mode is not one of the strings listed above. Some implementations define additional supported modes (e.g. Windows).

std::fscanf

Conversion
specifier
Explanation Argument type
length modifier hh

(C++11)

h (none) l ll

(C++11)

j

(C++11)

z

(C++11)

t

(C++11)

L
% matches literal % N/A N/A N/A N/A N/A N/A N/A N/A N/A
c
matches a character or a sequence of characters

If a width specifier is used, matches exactly width characters (the argument must be a pointer to an array with sufficient room). Unlike %s and %[, does not append the null character to the array.

N/A N/A
char*
wchar_t*
N/A N/A N/A N/A N/A
s
matches a sequence of non-whitespace characters (a string)

If width specifier is used, matches up to width or until the first whitespace character, whichever appears first. Always stores a null character in addition to the characters matched (so the argument array must have room for at least width+1 characters)

[set]
matches a non-empty sequence of character from set of characters.

If the first character of the set is ^, then all characters not in the set are matched. If the set begins with ] or ^] then the ] character is also included into the set. It is implementation-defined whether the character - in the non-initial position in the scanset may be indicating a range, as in [0-9]. If width specifier is used, matches only up to width. Always stores a null character in addition to the characters matched (so the argument array must have room for at least width+1 characters)

d
matches a decimal integer.

The format of the number is the same as expected by strtol() with the value 10 for the base argument

signed char* or unsigned char*
signed short* or unsigned short*
signed int* or unsigned int*
signed long* or unsigned long*
signed long long* or unsigned long long*
intmax_t* or uintmax_t*
size_t*
ptrdiff_t*
N/A
i
matches an integer.

The format of the number is the same as expected by strtol() with the value 0 for the base argument (base is determined by the first characters parsed)

u
matches an unsigned decimal integer.

The format of the number is the same as expected by strtoul() with the value 10 for the base argument.

o
matches an unsigned octal integer.

The format of the number is the same as expected by strtoul() with the value 8 for the base argument

x, X
matches an unsigned hexadecimal integer.

The format of the number is the same as expected by strtoul() with the value 16 for the base argument

n
returns the number of characters read so far.

No input is consumed. Does not increment the assignment count. If the specifier has assignment-suppressing operator defined, the behavior is undefined

a, A(C++11)
e, E
f, F
g, G
matches a floating-point number.

The format of the number is the same as expected by strtof()

N/A N/A
float*
double*
N/A N/A N/A N/A
long double*
p
matches implementation defined character sequence defining a pointer.

printf family of functions should produce the same sequence using %p format specifier

N/A N/A
void**
N/A N/A N/A N/A N/A N/A

std::fprintf

pointer to a null-terminated multibyte string specifying how to interpret the data.

The format string consists of ordinary multibyte characters (except %), which are copied unchanged into the output stream, and conversion specifications. Each conversion specification has the following format:

  • introductory % character
  • (optional) one or more flags that modify the behavior of the conversion:
  • -: the result of the conversion is left-justified within the field (by default it is right-justified)
  • +: the sign of signed conversions is always prepended to the result of the conversion (by default the result is preceded by minus only when it is negative)
  • space: if the result of a signed conversion does not start with a sign character, or is empty, space is prepended to the result. It is ignored if + flag is present.
  • # : alternative form of the conversion is performed. See the table below for exact effects otherwise the behavior is undefined.
  • 0 : for integer and floating point number conversions, leading zeros are used to pad the field instead of space characters. For integer numbers it is ignored if the precision is explicitly specified. For other conversions using this flag results in undefined behavior. It is ignored if - flag is present.
  • (optional) integer value or * that specifies minimum field width. The result is padded with space characters (by default), if required, on the left when right-justified, or on the right if left-justified. In the case when * is used, the width is specified by an additional argument of type int. If the value of the argument is negative, it results with the - flag specified and positive field width. (Note: This is the minimum width: The value is never truncated.)
  • (optional) . followed by integer number or *, or neither that specifies precision of the conversion. In the case when * is used, the precision is specified by an additional argument of type int. If the value of this argument is negative, it is ignored. If neither a number nor * is used, the precision is taken as zero. See the table below for exact effects of precision.
  • (optional) length modifier that specifies the size of the argument
  • conversion format specifier

The following format specifiers are available:

Conversion
specifier
Explanation Argument type
length modifier hh

(C++11)

h (none) l ll

(C++11)

j

(C++11)

z

(C++11)

t

(C++11)

L
% writes literal %. The full conversion specification must be %%. N/A N/A N/A N/A N/A N/A N/A N/A N/A
c
writes a single character.

The argument is first converted to unsigned char. If the l modifier is used, the argument is first converted to a character string as if by %ls with a wchar_t[2] argument.

N/A N/A
int
wint_t
N/A N/A N/A N/A N/A
s
writes a character string

The argument must be a pointer to the initial element of an array of characters. Precision specifies the maximum number of bytes to be written. If Precision is not specified, writes every byte up to and not including the first null terminator. If the l specifier is used, the argument must be a pointer to the initial element of an array of wchar_t, which is converted to char array as if by a call to wcrtomb with zero-initialized conversion state.

N/A N/A
char*
wchar_t*
N/A N/A N/A N/A N/A
d
i
converts a signed integer into decimal representation [-]dddd.

Precision specifies the minimum number of digits to appear. The default precision is 1.
If both the converted value and the precision are 0 the conversion results in no characters.

signed char
short
int
long
long long
intmax_t
signed size_t
ptrdiff_t
N/A
o
converts a unsigned integer into octal representation oooo.

Precision specifies the minimum number of digits to appear. The default precision is 1. If both the converted value and the precision are 0 the conversion results in no characters. In the alternative implementation precision is increased if necessary, to write one leading zero. In that case if both the converted value and the precision are 0, single 0 is written.

unsigned char
unsigned short
unsigned int
unsigned long
unsigned long long
uintmax_t
size_t
unsigned version of ptrdiff_t
N/A
x
X
converts an unsigned integer into hexadecimal representation hhhh.

For the x conversion letters abcdef are used.
For the X conversion letters ABCDEF are used.
Precision specifies the minimum number of digits to appear. The default precision is 1. If both the converted value and the precision are 0 the conversion results in no characters. In the alternative implementation 0x or 0X is prefixed to results if the converted value is nonzero.

N/A
u
converts an unsigned integer into decimal representation dddd.

Precision specifies the minimum number of digits to appear. The default precision is 1. If both the converted value and the precision are 0 the conversion results in no characters.

N/A
f
F
converts floating-point number to the decimal notation in the style [-]ddd.ddd.

Precision specifies the minimum number of digits to appear after the decimal point character. The default precision is 6. In the alternative implementation decimal point character is written even if no digits follow it. For infinity and not-a-number conversion style see notes.

N/A N/A
double
double (C++11)
N/A N/A N/A N/A
long double
e
E
converts floating-point number to the decimal exponent notation.

For the e conversion style [-]d.ddde±dd is used.
For the E conversion style [-]d.dddE±dd is used.
The exponent contains at least two digits, more digits are used only if necessary. If the value is 0, the exponent is also 0. Precision specifies the minimum number of digits to appear after the decimal point character. The default precision is 6. In the alternative implementation decimal point character is written even if no digits follow it. For infinity and not-a-number conversion style see notes.

N/A N/A N/A N/A N/A N/A
a
A

(C++11)

converts floating-point number to the hexadecimal exponent notation.

For the a conversion style [-]0xh.hhhp±d is used.
For the A conversion style [-]0Xh.hhhP±d is used.
The first hexadecimal digit is not 0 if the argument is a normalized floating point value. If the value is 0, the exponent is also 0. Precision specifies the minimum number of digits to appear after the decimal point character. The default precision is sufficient for exact representation of the value. In the alternative implementation decimal point character is written even if no digits follow it. For infinity and not-a-number conversion style see notes.

N/A N/A N/A N/A N/A N/A
g
G
converts floating-point number to decimal or decimal exponent notation depending on the value and the precision.

For the g conversion style conversion with style e or f will be performed.
For the G conversion style conversion with style E or F will be performed.
Let P equal the precision if nonzero, 6 if the precision is not specified, or 1 if the precision is 0. Then, if a conversion with style E would have an exponent of X:

  • if P > X ≥ −4, the conversion is with style f or F and precision P − 1 − X.
  • otherwise, the conversion is with style e or E and precision P − 1.

Unless alternative representation is requested the trailing zeros are removed, also the decimal point character is removed if no fractional part is left. For infinity and not-a-number conversion style see notes.

N/A N/A N/A N/A N/A N/A
n
returns the number of characters written so far by this call to the function.

The result is written to the value pointed to by the argument. The specification may not contain any flag, field width, or precision.

signed char*
short*
int*
long*
long long*
intmax_t*
signed size_t*
ptrdiff_t*
N/A
p writes an implementation defined character sequence defining a pointer. N/A N/A void* N/A N/A N/A N/A N/A N/A

The floating point conversion functions convert infinity to inf or infinity. Which one is used is implementation defined.

Not-a-number is converted to nan or nan(char_sequence). Which one is used is implementation defined.

The conversions F, E, G, A output INF, INFINITY, NAN instead.

Even though %c expects int argument, it is safe to pass a char because of the integer promotion that takes place when a variadic function is called.

The correct conversion specifications for the fixed-width character types (int8_t, etc) are defined in the header <cinttypes> (although PRIdMAX, PRIuMAX, etc is synonymous with %jd, %ju, etc).

The memory-writing conversion specifier %n is a common target of security exploits where format strings depend on user input and is not supported by the bounds-checked printf_s family of functions.

There is a sequence point after the action of each conversion specifier; this permits storing multiple %n results in the same variable or, as an edge case, printing a string modified by an earlier %n within the same call.

If a conversion specification is invalid, the behavior is undefined.

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章