用C++操作文件

来源:互联网 发布:系统优化的意义 编辑:程序博客网 时间:2024/06/07 00:10

用C++读写文件

C++ 通过以下几个类支持文件的输入输出:

  • ofstream: 写操作(输出)的文件类 (由ostream引申而来)
  • ifstream: 读操作(输入)的文件类(由istream引申而来)
  • fstream: 可同时读写操作的文件类 (由iostream引申而来)

一、打开文件

void open(const char* filename,int mode,int access);

参数:

filename: 要打开的文件名
mode: 要打开文件的方式
access: 打开文件的属性
打开文件的方式在类ios(是所有流式I/O类的基类)中定义,常用的值如下:

ios::app: 以追加的方式打开文件
ios::ate: 文件打开后定位到文件尾,ios:app就包含有此属性
ios::binary: 以二进制方式打开文件,缺省的方式是文本方式。两种方式的区别见前文
ios::in: 文件以输入方式打开
ios::out: 文件以输出方式打开
ios::nocreate: 不建立文件,所以文件不存在时打开失败
ios::noreplace:不覆盖文件,所以打开文件时如果文件存在失败
ios::trunc: 如果文件存在,把文件长度设为0
可以用“或”把以上属性连接起来,如ios::out|ios::binary 

打开文件的属性取值是:

0:普通文件,打开访问
1:只读文件
2:隐含文件
4:系统文件
可以用“或”或者“+”把以上属性连接起来 ,如3或1|2就是以只读和隐含属性打开文件。

例如:以二进制输入方式打开文件c:config.sys

fstream file1;
file1.open("c:config.sys",ios::binary|ios::in,0);

如果open函数只有文件名一个参数,则是以读/写普通文件打开,即:

file1.open("c:config.sys");<=>file1.open("c:config.sys",ios::in|ios::out,0);

另外,fstream还有和open()一样的构造函数,对于上例,在定义的时侯就可以打开文件了:

fstream file1("c:config.sys");

特别提出的是,fstream有两个子类:ifstream(input file stream)和ofstream(outpu file stream),ifstream默认以输入方式打开文件,而ofstream默认以输出方式打开文件。

ifstream file2("c:pdos.def");//以输入方式打开文件
ofstream file3("c:x.123");//以输出方式打开文件

所以,在实际应用中,根据需要的不同,选择不同的类来定义:如果想以输入方式打开,就用ifstream来定义;如果想以输出方式打开,就用ofstream来定义;如果想以输入/输出方式来打开,就用fstream来定义。


二、关闭文件


打开的文件使用完成后一定要关闭,fstream提供了成员函数close()来完成此操作,如:file1.close();就把file1相连的文件关闭。


三、读文本文件

数据格式1:

Name      score

Amily       9.8

Alen         9.5

对于数据格式1这类数据,我们可以用插入器(<<) 或者析取器(>>) 进行文件的读写。以上述数据为例,写一段读取该文本数据的代码

数据格式2:
I am from China.
This,line,test,getline,function
对于这种数据格式,使用getline函数较为合适,getline函数用法如下:
istream& getline (istream&  is, string& str, char delim);
istream& getline (istream&& is, string& str, char delim);
istream& getline (istream&  is, string& str);istream& getline (istream&& is, string& str);
查看函数声明很容易知道这些函数的用法,所以就不做详解,要进一步了解的话请参考:http://www.cplusplus.com/reference/string/string/getline/?kw=getline
四、写文本文件
对于文本文件而言,输出一般使用插入器(<<)进行输出。

四、操作输入输出流指针
对于输入流存在一个 get pointer 指向下一个待读入数据,对于输出流存在一个 put pointer 指向下一个数据待输出的位置。C++ 允许查看和修改这两个输入输出流指针,从而修改输入输出的位置。
tellg:获取输入流指针
tellp:获取输出流指针
seekg:重定位输入流指针
seekp:重定位输出流指针
 
1.istream& seekg (streampos pos);
 
2.istream& seekg (streamoff off, ios_base::seekdir way);
pos:绝对位置
New absolute position within the stream (relative to the beginning).
streampos is an fpos type (it can be converted to/from integral types).
off:相对偏移
Offset value, relative to the way parameter.
streamoff is an offset type (generally, a signed integral type).
way:确定相对偏移的参考点
Object of type ios_base::seekdir. It may take any of the following constant values: 
valueoffset is relative to...ios_base::begbeginning of the streamios_base::curcurrent position in the streamios_base::endend of the streamseekp的用法和上面的类似,更详细的使用请参考:http://www.cplusplus.com/reference/ostream/ostream/seekp/?kw=seekp

 五、读二进制文件

二进制文件是以byte为单位进行读写的。读写二进制文件时不能指定读写格式,因此常见的做法是把数据读写到指定的内存空间中,并且该内存空间对应于一个目标对象的存储空间。
C++提供了读写二进制文件的标准库函数:
istream& read (char* s, streamsize n):s 是要存储数据在内存中的首地址,n指定要读入的数据的byte数目
ostream& write (const char* s, streamsize n)

一般的使用方法: 

ifstream infile(“test.txt");

int a = 0;

infile.read((char*)a,sizeof(a));// 将流中的数据读入a中

基本上有了这些函数和输入输出流的定位函数就能对文件进行读写了。


六、扩展:用FILE对象对文件进行读写操作


七、复制、移动、删除文件

因为文件是属于系统所有,C++本身不能对文件进行操作,但是Windows为C++编写了操作系统的接口函数即API,通过调用API函数就可以只是操作系统完成目标操作


在C++中调用DOS系统,完成以上操作如:

system("copy /a sourceFile destinatedFile"); 更详细的命令请在命令窗口输入help copy 或者 copy /?


调用系统API函数:需要包含Windows.h头文件(一般而言使用系统API函数都需要包含Windows.h),参考文档:https://msdn.microsoft.com/en-us/library/windows/desktop/aa363851(v=vs.85).aspx

CopyFile:

Syntax

C++
BOOL WINAPI CopyFile(  _In_ LPCTSTR lpExistingFileName,  _In_ LPCTSTR lpNewFileName,  _In_ BOOL    bFailIfExists);

Parameters

lpExistingFileName [in]

The name of an existing file.

In the ANSI version of this function, the name is limited to MAX_PATH characters. To extend this limit to 32,767 wide characters, call the Unicode version of the function and prepend "\\?\" to the path. For more information, see Naming a File.

If lpExistingFileName does not exist, CopyFile fails, and GetLastError returns ERROR_FILE_NOT_FOUND.

lpNewFileName [in]

The name of the new file.

In the ANSI version of this function, the name is limited to MAX_PATH characters. To extend this limit to 32,767 wide characters, call the Unicode version of the function and prepend "\\?\" to the path. For more information, see Naming a File.

bFailIfExists [in]

If this parameter is TRUE and the new file specified by lpNewFileName already exists, the function fails. If this parameter is FALSE and the new file already exists, the function overwrites the existing file and succeeds.

Return value

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

MoveFile:

Syntax

C++
BOOL WINAPI MoveFile(  _In_ LPCTSTR lpExistingFileName,  _In_ LPCTSTR lpNewFileName);//详细说明参见:https://msdn.microsoft.com/en-us/library/windows/desktop/aa365239(v=vs.85).aspx

DeleteFile():

Syntax

C++
BOOL WINAPI DeleteFile(  _In_ LPCTSTR lpFileName);详细说明请参见:https://msdn.microsoft.com/en-us/library/windows/desktop/aa363915(v=vs.85).aspx


rename:

rename(const char* oldFileName,const char* destFileName);

这个函数见文知意。

更多函数参见https://msdn.microsoft


 





0 0