Chinaunix首页 | 论坛 | 博客
  • 博客访问: 680193
  • 博文数量: 103
  • 博客积分: 2532
  • 博客等级: 大尉
  • 技术积分: 2039
  • 用 户 组: 普通用户
  • 注册时间: 2008-11-26 16:07
文章分类

全部博文(103)

文章存档

2012年(38)

2011年(28)

2010年(16)

2009年(16)

2008年(5)

分类: C/C++

2011-05-06 09:41:09

一、定义文件指针: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




阅读(884) | 评论(1) | 转发(0) |
给主人留下些什么吧!~~

fychit2011-05-06 09:59:28

判断文件是否存在:access(filename,0),头文件#include 删除文件:remove(filename);