文件管理(1)

1、为什么要使用文件

之前写的通讯录,无论是静态版本,还是动态增长版本。通讯录的信息都是放在【内存】中的,程序退出后,再次运行,又要重新输入数据 。而如果将数据写到文件中,就可以持久化了(这时的数据是存储在硬盘上的)。

2、什么是文件

在程序设计中,按照文件功能的不同分为:程序文件和数据文件。
(1)程序文件
源程序文件(后缀为 .c)\ 目标文件(windows环境下后缀为 .obj)\ 可执行程序(windows环境下后缀为 .exe)
(2)数据文件
文件的内容不一定是程序,而是程序运行时读写的数据。例如程序运行时需要从中读取数据的文件,或者输出数据的文件。
(3)文件名
例如:c:\code\test.txt
c:\code(文件路径) test(文件名主干) .txt(文件后缀)

3、文件的打开和关闭

3.1 文件指针

每个被使用的文件都在内存中开辟了一个相应的文件信息区,用来存放文件的相关信息(如文件名字、文件状态和文件当前的位置)。这些信息是保存在一个结构体变量中的,该结构体类型是有系统申明,取名为:FILE 。每打开一个文件的时候,系统会根据文件的情况自动创建一个FILE结构的变量,并填充其中的信息,使用者不必过度关心细节。

通过文件指针(FILE* pf)来维护文件信息区, pf指向文件信息区的地址。通过文件指针变量能够找到与它相关联的文件。

3.2 文件的打开和关闭

文件在读写之前应该先打开文件,在使用结束之后应该关闭文件。

打开文件:fopen:Open a file.
fopen在打开文件的同时,创建了该文件的文件信息区,并将文件信息区的地址返回。
类型:FILE* fopen( const char* filename, const char* mode )
fopen returns a pointer to the open file;\ filename:Filename;\ mode:Type of access permitted

关闭文件:fclose: close a file.
类型:int fclose( FILE *stream )
fclose returns 0 if the stream is successfully closed. \ stream: Pointer to FILE structure.

4、文件的顺序读写:顺序输入、输出函数

//   功能                   函数名                 适用于
//字符输入函数              fgetc                所有输入流
//字符输出函数              fputc                所有输出流
//文本行输入函数            fgets                所有输入流
//文本行输出函数            fputs                所有输出流
//格式化输入函数            fscanf               所有输入流
//格式化输出函数            fprintf              所有输出流
//二进制输入                fread                   文件
//二进制输出                fwrite                  文件

4.1 写文件—输出操作:fputc

//fputc: Writes a character to a stream 
//类型:int fputc( int c, FILE *stream );
//fputc:returns the character written. \ c:Character to be written. \ stream:Pointer to FILE structure.

#include <stdio.h>
int main()
{
//打开文件
	FILE* pf = fopen("D:\\test.txt","w"); 
	if (NULL==pf)
	{
		perror("fopen");
		return 1;
	}
//写文件
	char ch = 'a';
	for (ch = 'a';ch<='z';ch++)
	{
		fputc(ch,pf); //fputc: Writes a character to a stream 
	}

//关闭文件
	fclose(pf);
	pf = NULL;	
	return 0;
}

4.2 读文件:输入操作,fgetc

//fgetc:Read a character from a stream 
//类型:int fgetc( FILE *stream );
// stream : Pointer to FILE structure
//fgetc returns the character read as an int or return EOF to indicate an error or end of file.

#include <stdio.h>
int main()
{
//打开文件
	FILE* pf = fopen("D:\\test.txt","r"); 
	if (NULL==pf)
	{
		perror("fopen");
		return 1;
	}
//读文件
	int ch = 0;
	while ((ch=fgetc(pf))!=EOF) //fgetc : Read a character from a stream 
	{
		printf("%c ",ch);
	}

//关闭文件
	fclose(pf);
	pf = NULL;
	return 0;
}

//从键盘上读取
#include <stdio.h>
int main()
{
	int ch = fgetc(stdin); //fgetc适合于所有输入流
	/*printf("%c",ch);*/
	fputc(ch,stdout);     //fputc适合于所有输出流

	return 0;
}

4.3 写文件:文本行输出函数-- fputs

// fputs:Write a string to a stream.
// fputs returns a nonnegative value if it is successful. On an error, fputs returns EOF.
// 类型:int fputs( const char *string, FILE *stream );
// string:Output string \ stream:Pointer to FILE structure;

#include <stdio.h>
int main()
{
//打开文件
	FILE* pf = fopen("D:\\test.txt","w"); //以“w”的模式打开文件,会自动销毁原文件中的内容。
	if (NULL==pf)
	{
		perror("fopen");
		return 1;
	}
//写文件 — 一次写一行
	fputs("abcdefgh\n",pf);
	fputs("********\n",pf);

//关闭文件
	fclose(pf);
	pf = NULL;

	return 0;
}

4.4 读文件:文本行输入函数: fgets

//fgets: Get a string from a stream.
//fgets:returns string.NULL is returned to indicate an error or an end - of - file condition.
//类型:char *fgets( char *string, int n, FILE *stream );
// string: Storage location for data \ n: Maximum number of characters to read \ stream:Pointer to FILE structure

#include <stdio.h>
int main()
{
	char arr[256] = {0};
	//打开文件
	FILE* pf = fopen("D:\\test.txt", "r"); 
	if (NULL == pf)
	{
		perror("fopen");
		return 1;
	}
	//读文件 — 一次读一行
	/*fgets(arr,256,pf);
	printf("%s",arr);*/

	while (fgets(arr, 256, pf) != NULL)
	{
		printf("%s",arr);
	}

	//关闭文件
	fclose(pf);
	pf = NULL;

	return 0;
}

4.5 写文件 — fprintf: 格式化输出函数

// fprintf:Print formatted data to a stream.
// fprintf returns the number of bytes written.This function returns a negative value instead when an output error occurs.
//type:int fprintf( FILE *stream, const char *format [, argument ]...);
//stream :Pointer to FILE structure \ format: Format-control string(格式控制字符串) \arguments: Optional arguments(参数)

#include <stdio.h>
struct S
{
	char name[20];
	int age;
	double d;
};

int main()
{
	struct S s = {"张三", 20, 95.5};
	//打开文件
	 FILE* pf= fopen("D:\\test.txt","w");
	 if (NULL==pf)
	 {
		 perror("fopen");
		 return 1;
	 }
	//写文件(格式化输出)
	fprintf(pf,"%s %d %lf",s.name, s.age, s.d);
	
	//关闭文件
	 fclose(pf);
	 pf = NULL;
	return 0;
}

4.6 读文件 — fscanf:格式化输入函数

// fscanf:Read formatted data from a stream.
//fscanf returns the number of fields successfully converted and assigned; the return value does not include fields that were read but not assigned. 
//A return value of 0 indicates that no fields were assigned. If an error occurs, or if the end of the file stream is reached before the first conversion, the return value is EOF for fscanf.
//类型:int fscanf( FILE *stream, const char *format [, argument ]... );
//stream :Pointer to FILE structure \ format: Format-control string(格式控制字符串) \arguments: Optional arguments(参数)

#include <stdio.h>
struct S
{
	char name[20];
	int age;
	double d;
};

int main()
{
	struct S s = {0};
	//打开文件
	FILE* pf = fopen("D:\\test.txt", "r");
	if (NULL == pf)
	{
		perror("fopen");
		return 1;
	}
	//读文件(格式化输入)
	fscanf(pf, "%s %d %lf", s.name, &(s.age), &(s.d));
	printf("%s %d %lf\n",s.name,s.age,s.d);

	//关闭文件
	fclose(pf);
	pf = NULL;
	return 0;
}

4.7 写文件 —fwrite: 二进制输出

// fwrite :Writes data to a stream.
// fwrite returns the number of full items actually written, which may be less than count if an error occurs. Also, if an error occurs, the file-position indicator cannot be determined.
// type:size_t fwrite( const void *buffer, size_t size, size_t count, FILE *stream );
// buffer:Pointer to data to be written \  size:Item size in bytes \ count: Maximum number of items to be written \ stream:Pointer to FILE structure

#include <stdio.h>
struct S
{
  char name[20];
  int age;
  double d;
};

int main()
{
	struct S s = {"张三",20,95.5};
	//打开文件
	FILE* pf = fopen("test.txt","wb");
	if (NULL==pf)
	{
		perror("fopen");
		return 1;
	}
	
	//二进制的方式写文件
	fwrite(&s,sizeof(struct S),1,pf);

	//关闭文件
	fclose(pf);
	pf == NULL;
	return 0;
}

4.8 读文件— fread:二进制输入

// fread :Reads data from a stream.
// fread returns the number of full items actually read, which may be less than count if an error occurs or 
// if the end of the file is encountered before reaching count.If size or count is 0, fread returns 0 and the buffer contents are unchanged.
//type:size_t fread( void *buffer, size_t size, size_t count, FILE *stream );
// buffer:Storage location for data   \  size:Item size in bytes  \  count:Maximum number of items to be read  \  stream: Pointer to FILE structure

#include <stdio.h>
struct S
{
	char name[20];
	int age;
	double d;
};

int main()
{
	struct S t = {0};
	//打开文件
	FILE* pf = fopen("test.txt", "rb");
	if (NULL == pf)
	{
		perror("fopen");
		return 1;
	}

	//二进制的方式读文件
	fread(&t, sizeof(struct S), 1, pf);
	printf("%s %d %lf",t.name,t.age,t.d);

	//关闭文件
	fclose(pf);
	pf = NULL;
	return 0;
}

4.9 辨析三组函数

// scanf -- 格式化输入函数       sprintf -- 格式化输出函数
// fscanf -- 针对所有输入流的格式化输入函数     fprintf -- 针对所有输出流的格式化输出函数
// sscanf -- 将一个字符串转化为格式化的数据    sprintf -- 将一个格式化的数据转化为字符串

//sprintf:输出 -- Write formatted data to a string.
//sprintf returns the number of bytes stored in buffer, not counting the terminating null character. 
//type:int sprintf( char *buffer, const char *format [, argument] ... );
// buffer:Storage location for output. \  format: Format-control string(格式控制字符串) \ arguments: Optional arguments(参数)

//sscanf:输入 -- Read formatted data from a string.
//sscanf returns the number of fields successfully converted and assigned; the return value does not include fields that were read but not assigned. A return value of 0 indicates 
//that no fields were assigned. The return value is EOF for an error or if the end of the string is reached before the first conversion.
//type:int sscanf( const char *buffer, const char *format [, argument ] ... );
// buffer: Stored data \  format: Format-control string(格式控制字符串) \ arguments: Optional arguments(参数)
//

#include <stdio.h>
struct S
{
	char name[20];
	int age;
	double d;
};

int main()
{
	char buf[256] = {0};
	struct S s = {"zhangsan",20,95.5};
	sprintf(buf,"%s %d %lf",s.name,s.age,s.d); //将结构体数据转化为字符串,存储在buf数组中
	printf("%s\n",buf);

	struct S t = {0};
	sscanf(buf,"%s %d %lf",s.name, &(s.age), &(s.d));//从buf字符串中提取结构体数据
	printf("%s\n", buf);
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值