c语言文件操作(1)

1.文件类型指针:

文件类型指针简称文件指针,文件指针的创建:

FILE *pf;

2.文件的打开与关闭:

文件的打开需要用到fopen函数,文件的关闭需要用到fclose函数


FILE * fopen ( const char * filename, const char * mode )

int fclose ( FILE * stream );

mode是文件的打开模式,以下都是文件的打开模式:

代码展示:

#include <stdio.h>

int main()
{
	FILE* pFile;
	pFile = fopen("test.txt", "w");
	if (pFile != NULL)
	{
		fputs("File Exam", pFile);
		fclose(pFile);
	}
	return 0;
}

这里只展示了‘w'的用法,其余的还需要各位直接去亲自练练。

3.文件的顺序读写

顺序读写函数:

fgets函数:从文本文件中读取数据

char * fgets ( char * str, int num, FILE * stream );

 代码展示:

#include <stdio.h>

int main()
{
   FILE * pFile;
   char mystring [10];

   pFile = fopen ("myfile.txt" , "r");
   if (pFile == NULL) perror ("Error opening file");
   else {
     if ( fgets (mystring , 100 , pFile) != NULL )
       puts (mystring);
     fclose (pFile);
   }
   return 0;
}

结果展示:

 fputs函数:将数据输出到文本文件中

int fputs ( const char * str, FILE * stream );

代码展示:

#include <stdio.h>

int main()
{
	FILE* pFile;
	char sentence[13];

	printf("Enter sentence to append: ");
	fgets(sentence, 13, stdin);
	pFile = fopen("mylog.txt", "a");
	fputs(sentence, pFile);
	fclose(pFile);
	return 0;
}

结果展示:

举例到这,其它还需自行体会。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值