手机做网站/域名查询官网
一、定义文件指针:FILE *fp;
二、打开文件
fp=fopen("file_name","open_mode");
file_name:要打开的文件名
open_mode:打开方式,r只读打开,w只写打开
if(!fp)
{
printf("文件打开失败!\n");
return 1;
}
三、文件读写
====================读写文件======================
1.ASCII文件读写
格式化输出到文件中:fprintf(fp,"输出格式",输出变量);
fprintf(fp,"%d\r\n",i);//以字符的形式写入到文件
\r\n表示输出到文件后回车换行
格式化从文件中读取:fscanf(fp,"输入格式",输入变量地址);
fscanf(fp,"%d\r\n",&k);
2.二进制文件读写
fread(变量地址,变量大小,变量个数,fp);//从文件中读数据
fwrite(变量地址,变量大小,变量个数,fp);//将数据写入文件中
================================================================
四、关闭文件:fclose(fp);
FILE *fopen( const char *filename, const char *mode );
FILE *_wfopen( const wchar_t *filename, const wchar_t *mode );
Parameters:
filename
Filename.
mode
Type of access permitted.
The character string mode specifies the type of access requested for the file, as follows:"r"Opens for reading. If the file does not exist or cannot be found, the fopen call fails."w"Opens an empty file for writing. If the given file exists, its contents are destroyed."a"Opens for writing at the end of the file (appending) without removing the EOF marker before writing new data to the file; creates the file first if it doesn't exist."r+"Opens for both reading and writing. (The file must exist.)"w+"Opens an empty file for both reading and writing. If the given file exists, its contents are destroyed."a+"Opens for reading and appending; the appending operation includes the removal of the EOF marker before new data is written to the file and the EOF marker is restored after writing is complete; creates the file first if it doesn't exist.
Characters in mode string
Equivalent oflag value for _open/ _sopen
a
_O_WRONLY | _O_APPEND(usually
_O_WRONLY | _O_CREAT | _O_APPEND)
a+
_O_RDWR | _O_APPEND (usually
_O_RDWR | _O_APPEND | _O_CREAT)
r
_O_RDONLY
r+
_O_RDWR
w
_O_WRONLY (usually _O_WRONLY | _O_CREAT | _O_TRUNC)
w+
_O_RDWR (usually _O_RDWR | _O_CREAT | _O_TRUNC)
b
_O_BINARY
t
_O_TEXT
c
None
n
None
S
_O_SEQUENTIAL
R
_O_RANDOM
T
_O_SHORTLIVED
D
_O_TEMPORARY
ccs=UNICODE
_O_WTEXT
ccs=UTF-8
_O_UTF8
ccs=UTF-16LE
_O_UTF16