您的位置:首页 > 编程语言 > C语言/C++

C语言fopen函数了解

2016-05-24 10:20 441 查看
fopen()函数功能:open a file.
原型:FILE * fopen(const char * path,const char * mode);

需要#include<stdio.h>

返回值:文件顺利打开后,指向该流的文件指针就会被返回。如果文件打开失败则返回NULL,并把错误代码存在errno 中。

一般打开文件会进行读取或写入操作,如果打开文件失败,也就无法顺利进行相应的读写操作,所以一般在调用fopen()之后要作错误判断及处理。

参数path字符串包含欲打开的文件路径及文件名,参数mode字符串则代表着流形态。

mode有以下几种形态

"r" Opens for reading. If the file does not exist or cannot be found, thefopen 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."b"  Open in binary (untranslated) mode; translations involving carriage-return and linefeed characters are suppressed. 文本模式和二进制模式的区别:1.在windows系统中,文本模式下,文件以"\r\n"代表换行。若以文本模式打开文件,并用fputs等函数写入换行符"\n"时,函数会自动在"\n"前面加上"\r"。即实际写入文件的是"\r\n" 。2.在类Unix/Linux系统中文本模式下,文件以"\n"代表换行。所以Linux系统中在文本模式和二进制模式下并无区别。

DEMO示例1:

#include <stdio.h>
#include <stdlib.h>
#include <process.h>
int main()
{
char ch;
FILE *fp;
char fname[50];   // store file name
printf("input file name:");
scanf("%s",fname);
fp=fopen(fname,"r");
if (fp==NULL)
{
printf("error!\n");
getchar();
getchar();
exit(1);
}
//getc()用于在打开文件中获取一个字符
while((ch=getc(fp))!=EOF)
{
putchar(ch);
}
printf("\n");
fclose(fp);
fp=NULL;
system("pause");
return 0;
}


DEMO2:

#include <stdio.h>
FILE *stream,*stream2;
int main(void)
{
int numclosed;
if ((stream=fopen("data.txt","r"))==NULL)
{
printf("The file 'data.txt' was not opened\n");
}
else
{
printf("The file 'data.txt' was  opened\n");
}

if ((stream2=fopen("data2.txt","w+"))==NULL)
{
printf("The file 'data2.txt' was not opened\n");
}
else
{
printf("The file 'data2.txt' was  opened\n");
}
if (stream)
{
if (fclose(stream))
{
printf("The file data.txt was not opened\n");
}
}
numclosed = _fcloseall();
printf("Number of files close by _fcloseall %u\n",numclosed);
system("pause");
return 0;
}


文件操作时需要注意以下几点:  1、在定义文件指针时,要将文件指针指向空;如 FILE *fp = NULL;

 

  2、文件操作完成后,需要将文件关闭,一定要注意,否则会造成文件所占用内存泄露和在下次访问文件时出现问题。

 

  3、文件关闭后,需要将文件指针指向空,这样做会防止出现游离指针,而对整个工程造成不必要的麻烦;如:fp = NULL;

【FROM MSDN && 百科】
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: