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

C语言中常用文件操作函数

2016-12-15 16:24 627 查看
最近在学习C语言,现将主要用到的文件操作的函数使用方法总结如下:

1.文件的打开与关闭

函数fopen(),fclose().

fopen(“path”,”mode”);

path:文件名,可以包含路径;mode:文件打开的方式。

对文本文件:

“r”:只读(文件已经存在)

“w”:只写(文件可以存在,也可不存在,存在则覆盖,不存在则创建)

“a”:追加(文件可以存在,也可不存在,在文件的末尾追加内容)

“r+”:读写(文件的头部开始)

“w+”:读写(覆盖)

“a+”:读写(追加)

对二进制文件:

“rb”:只读

“wb”:只写(覆盖)

“ab”:追加

“rb+”:读写(文件的头部开始)

“wb+”:读写(覆盖)

“ab+”:读写(追加)

FILE *p = NULL;
fp = fopen("a.txt","w");
fclose(fp);


注:在操作一个或多个文件的时候,在程序退出之前,应将所有打开的文件用fclose()函数关闭。

2.文件的读写

函数fputc(),fgetc(),fputs(),fgets().

fputc():将一个字符写到文件中。例子如下:

#include <stdio.h>
int main()
{
FILE *fp = NULL;
char str[50] = "hviosknd";
if ((fp=fopen("a.txt","w"))==NULL)//w:覆盖原内容,a:在原内容后面追加
{
printf("error\n");
return 0;
}
else
{
printf("success\n");
}
while (str[i]!='\0')
{
fputc (str[i],fp);//fputc将字符写到文件中
i++;
}
fclose(fp);
return 0;
}


fgetc():从文件中读一个字符出来。

#include <stdio.h>
#include <stdlib.h>
int main()
{
char c;
FILE *fp = NULL;
if ((fp = fopen("test.txt","r"))!=NULL)
{
printf("打开文件失败!\n");
return 0;
}
printf("打开文件成功!\n");
while(1)
{
c = fgetc(fp);
if(c==EOF)
break;
else
printf("%c",c);
}
fclose(fp);
system("pause");
return 0;
}


fgets():从指定文件中读取一个字符串。

char str[50] = "abcdefg";
fgets(str,n,fp);//n位指定读取的字符个数,但fp只能读出n-1个,最后加'\0',如果在读入n-1个字符之前已经遇到了EOF,读入结束返回str的首地址。


fputs():往文件中写入一个字符串。

fputs("abcdefg",fp);//成功返回非负数,失败返回EOF。


此外,还有fread(),fwrite()函数。

fread(buffer,size,count,fp);

fwrite(buffer,size,count,fp);

//buffer:缓冲区,保存了读出来或即将写入的数据;size:读写一次的字节数;count:进行多少次读写;fp:文件指针。

例:使用fwrite()将两个整数写到文件中,并用fread()读出来。

#include <stdio.h>
int main ()
{
int i = 15,j = 30;
FILE *fp = NULL;
if ((fp = fopen("b.txt","w"))==NULL)
{
printf("fail to open the file: %m\n");
return 0;
}
else
{
printf("success to open the file.\n");
}
if ((fread(&i,sizeof(i),1,fp))==1)
{
printf("读取失败\n");
}
//rewind(fp);//rewind()函数使位置指针回到文件的开头

if ((fread(&j,sizeof(j),1,fp))==1)
{
printf("读取失败\n");
}
fwrite(&i,sizeof(i),1,fp);
fwrite(&j,sizeof(j),1,fp);
printf("i = %d,j = %d\n",i,j);
fclose(fp);
return 0;
}


3.文件的定位

(1)rewind():使位置指针回到文件的开头。

rewind(fp);


(2)fseek(fp,offset,whence);

fp:文件指针;offset:位移量;whence:起始点(SEEK_SET(文件开头),SEEK_CUR(当前位置),SEEK_END(文件末尾))。

fseek(fp,100,SEEK_CUR);

fseek(fp,sizeof(struct student),SEEK_SET);


4.获取键盘输入的字符

函数getchar(),putchar().

/*当输入的字符不为空格时,其ASCII加1*/
#include <stdio.h>
#include <stdlib.h>
#define space ' '
int main(void)
{
char ch;
ch=getchar();
while(ch!='\n')
{
if(ch==space)
putchar(ch);
else
putchar(ch+1);

ch=getchar();
}
putchar(ch);
system("pause");
return 0;
}


另外,还有最基本的scanf(
4000
)和printf()输入输出函数,语法较简单。

char name[20];

printf("Please enter your name:\n");

scanf("%s",&name);


以上即是本人整理的C语言中常用文件操作的函数,正在学习中。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: