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 appendixmode
)
Return
std::FILE*
(For details, please check the entrystd::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 entrystd::FILE
)const char* format
(For details, please check the appdendixstd::fscanf
)...
(received arguments)
Return
int
Number of receiving arguments successfully assigned (which may be0
in case a matching failure occurred before the first receiving argument was assigned), orEOF
if 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,EOF
otherwise
std::gets
<cstdio>
Reference:
std::fopen
Warning: You’d better use
std::fgets
instead ofstd::gets
for its unsecurity of buffer overflowing. For details, please checkstd::fgets
.
Header
char* gets( char* str );
Parameter
char* str
character string to be written
Return
char*
str
on success,NULL
on failure.
If the failure has been caused by end of file condition, additionally sets theeof
indicator (seestd::feof
) onstdin
.
If the failure has been caused by some other error, sets the error indicator (seestd::ferror
) onstdin
.
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 appendixstd::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 entrystd::fopen
) or the appendixmode
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::fseek
indicating seeking from beginning of the file
SEEK_CUR
Argument to std::fseek
indicating seeking from the current file position
SEEK_END
Argument to std::fseek
indicating 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 |
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 |
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] |
If the first character of the set is | |||||||||
d |
The format of the number is the same as expected by strtol() with the value 10 for the |
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 |
The format of the number is the same as expected by strtol() with the value 0 for the | |||||||||
u |
The format of the number is the same as expected by strtoul() with the value 10 for the | |||||||||
o |
The format of the number is the same as expected by strtoul() with the value 8 for the | |||||||||
x , X |
The format of the number is the same as expected by strtoul() with the value 16 for the | |||||||||
n |
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 |
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 |
| 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
The following format specifiers are available:
The floating point conversion functions convert infinity to Not-a-number is converted to The conversions Even though 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 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 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.
|