文件操作(汇总)

1. 首先讲述一个小技巧,查找MSDN库的方法,点击关键字,按F1键,会自动打开在线帮助系统。

    当然你也可以离线下载好之后再用。

2. 文件的打开和关闭: fopen()函数 和 fclose()函数

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

参数:filename --- 文件名 (file name)

           mode --- 访问文件的方式 (kind of access file that's enabled)

返回值:文件指针 返回NULL指针表示有错误出现。

Unicode support:

//fopen support Unicode file streams. To open a Unicode file,pass a ccs flag that specifies the desired encoding to open:
  FILE *fp = fopen("file.txt", "rt+, ccs=encoding");
//Allowed values of encoding are Unicode,UTF-8, and UTF-16LE.

The character string mode specifies the kind of access that is requested for the file:

"r"     Opens for reading. If the file does not exist or cannot be found, the fopen call fails.

         文件必须存在且能找到(路径正确)

"w"    Opens an empty file for writing. If the given file exists, its contents are destroyed.

         如果文件不存在,会新建文件再写入新内容

         如果文件存在,会清空文件以前的内容再写入新的内容

int main()
{
	
	FILE *file;
	file = fopen("file1.txt","w");
	char c = 97;
	for(int i=0;i<20;i++)
	{
		fputc(c,file);
		c++;
	}
	fclose(file);
	system("pause");
	return 0;
}

输出:abcdefghijklmnopqrst

"a"     

          Opens for writing at the end of the file(appending) without removing the end-of-file(EOF) marker before new data is written to the file.

          Creates the file if it does not exist.

"r+"    

          Opens for both reading and writing.The file must exist.

"w+"  

          Opens an empty file for both reading and writing.If the file exists,its contents are destroyed.

"a+"

          Opens for reading and appending.The appending operation includes the removal of the EOF(CTRL+Z) marker before new data is written to the file.

          Creates the file if it does not exist.

t         

          Open in text (translated) mode.

b

          Open in binary (untranslated) mode.

int fclose(FILE *stream);

3. 文件的读写操作

读文件函数:fread(), fgetc(), fgets()

1)从文件流中读取字节到buffer中 --- Reads data from a stream.

size_t fread(void *buffer, size_t size, size_t count, FILE *stream);

The fread function reads up to count items of size bytes from the input stream and stores them in buffer.

The file pointer associated with stream is incremented by the number of bytes actually read.

This function locks out other threads. If you need a non-locking version, use _fread_nolock.

函数参数:

                buffer --- Storage location for data.

                size --- Item size in bytes.

                count --- Maximum number of items to be read.

                stream --- Pointer to FILE structure.

返回值:返回实际读到的items的个数,有可能会小于count当error出现或者遇到EOF的时候。

int main()
{	
	FILE *file;
	file=fopen("file.txt","r");
	char ch[50];//定义一个字符数组
	fread(ch,1,20,file);//从file中读取20个字节到ch中
	ch[20]='\0';
	puts(ch);
	fclose(file);
	system("pause");
	return 0;
}

输出:abcdefghijklmnopqrst

2)读取单个字符:

int fgetc(FILE *stream);

从文件流stream中读取单个字符,返回值是读到字符的ASCII值。

int main()
{	
	FILE *file;
	file=fopen("file.txt","r");
	char ch[50];//定义一个字符数组
	char c;
	int i;
	for(i=0;!feof(file);i++)
	{
		c=fgetc(file);
		ch[i]=c;
	}
	ch[i]='\0';
	puts(ch);
	fclose(file);
	system("pause");
	return 0;
}

输出结果同上。

3)读取字符串 --- fgets

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

The fgets function reads a string from the input stream argument and stores it in str.

The result stored in str is appended with a null character.

读到n-1个字符时停止,后面要追加null字符。

函数参数:

               str: Storage location for data

               n: Maximum number of characters to read.

               stream: Pointer to FIFE structure.

返回值:字符指针,指向读到的字符串。

int main()
{	
	FILE *file;
	file=fopen("file.txt","r");
	char ch[50];//定义一个字符数组
	fgets(ch,15,file);//会在末尾自动加‘\0’	
	puts(ch);
	fclose(file);
	system("pause");
	return 0;
}

输出结果:abcdefghijklmn

写文件函数:fwrite(), fputc(), fputs().

1) fwrite: Writes data to a stream.

size_t fwrite(const void *buffer, size_t size, size_t count, FILE *stream);

The fwrite function writes up to count items, of size length each, from buffer to the output stream.

The file pointer associated with stream is incremented by the number of bytes actually written.

函数参数:

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.

int main()
{	
	FILE *file;
	file=fopen("file.txt","w+");
	char ch[50] = "He is a clever boy!";//定义一个字符数组
	fwrite(ch,1,15,file);//会在末尾自动加‘\0’	
	fclose(file);
	file=fopen("file.txt","r");
	char rech[20];
	fgets(rech,15,file);
	puts(rech);
	fclose(file);
	system("pause");
	return 0;
}

输出结果:He is a clever

2) 写单个字符fputc()和写字符串fputs()

int fputc(int c, FILE *stream);

Writes the single character c to a file at the position indicated by the associated file position indicator.

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

Copies str to the output stream at the current position.

int main()
{	
	FILE *file;
	file=fopen("file.txt","w+");
	char ch[20] = "He is a clever boy!";//定义一个字符数组
	fwrite(ch,1,19,file);//文件指针会移动	
	char rech[30] = "He looks like his father.";
	for(int i=0;i<25;i++)
	{
		fputc(rech[i],file);//写入单个字符
	}
	fclose(file);
	file=fopen("file.txt","a+");//以追加模式打开文件
	fputs(ch,file);
	fclose(file);
	file=fopen("file.txt","r");
	char readch[100];
	fread(readch,1,63,file);
	readch[63]='\0';
	puts(readch);
	fclose(file);
	system("pause");
	return 0;
}

输出结果:He is a clever boy!He looks like his father.He is a clever boy!

注意:fread()和fwrite()会改变文件指针的位置,所以改变后可以再读或再写。

           而fputc(),fputs(),fgetc().fgets()是读写到文件缓冲区内,要等到文件关闭后内容才会生效。

 

4. 文件指针的移动fseek(),rewind()

int fseek(FILE *stream, long offset, int origin);

Moves the file pointer to a specified location that is offset bytes from origin.

函数参数:

               stream: Pointer to FILE structure.

               offset: Number of bytes from origin.

               origin: Initial position.

                          SEEK_CUR --- Current position of file pointer.

                          SEEK_END --- End of file.

                          SEEK_SET --- Beginning of file.

返回值:移动成功,返回0,否则返回非0值。

void rewind(FILE *stream);

Repositions the file pointer to the beginning of a file.

A call to rewind is similar to (void) fseek(stream,0L,SEEK_SET);

int main()
{	
	FILE *file;
	file=fopen("file.txt","w+");
	char ch[20] = "He is a clever boy!";//定义一个字符数组
	fwrite(ch,1,19,file);//文件指针会移动	
	char rech[30] = "He looks like his father.";
	for(int i=0;i<25;i++)
	{
		fputc(rech[i],file);//写入单个字符
	}
	fclose(file);
	file=fopen("file.txt","r");
	fseek(file,8,SEEK_SET);
	char gch[50];
	fgets(gch,50,file);
	puts(gch);
	rewind(file);
	fgets(gch,50,file);
	puts(gch);
	fclose(file);	
	system("pause");
	return 0;
}

输出结果:

5. 文件结束feof()

int feof(FILE *stream);

Tests for end-of-file on a stream.

结束返回非0值,未结束返回0.

The feof function returns a nonzero value if a read operation has attempted to read past the end of file, otherwise it returns 0.

#include <iostream>
using namespace std;

int main()
{
	FILE *fp;
	char *s1 = "Fortran",*s2 = "Basic";
	if((fp = fopen("test.txt","wb"))==NULL)
	{
		printf("Can't open test.txt file\n");
		exit(1);
	}
	fwrite(s1,7,1,fp);//把从地址s1开始的7个字符写到fp所指文件中
	fseek(fp,0L,SEEK_SET);//文件位置指针移到文件开头
	fwrite(s2,5,1,fp);
	fclose(fp);
	system("pause");
	return 0;
}

test.txt中的内容是:Basican
 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值