文件操作

http://www.runoob.com/cprogramming/c-file-io.html

1. 创建文件,并写入内容:

#include <stdio.h>

int main()
{
	FILE *fp = NULL;	// 声明一个文件指针
	// 创建/打开文件,定义文件指针,可向文件中写入内容,要保证相对路径tmp/test.txt
	fp = fopen("tmp/test.txt", "w+");	

	fprintf(fp, "This is testing for fprintf...\n");	// 写入
	fputs("This is testing for fputs...\n", fp);		// 写入

	fclose(fp);		// 关闭文件
}

  

 

2. 读取文件内容:读取全部内容

 文件:

 

#include <stdio.h>

int main()
{
	FILE *fp = NULL;	// 声明一个文件指针
	char buff[ 255 ];	// 存放读取到的字符串

	// 读取文件tmp/test.txt
	fp = fopen("tmp/test.txt", "r");	

	// 使用 fscanf() 函数来读取文件,遇到空格会停止读取
	//fscanf(fp, "%s", buff);
	//printf("使用 fscanf() 函数读取:%s \n", buff);

	// 使用 fgets() 函数来读取文件,遇到空格会停止读取
	while(!feof(fp))
	{	
		fgets(buff, 255, fp);
		printf("使用 fgets() 函数读取:%s", buff);
	}

	fclose(fp);		// 关闭文件
}

 读取:

 

posted @ 2018-02-24 13:37  半生戎马,共话桑麻、  阅读(138)  评论(0)    收藏  举报
levels of contents