Welcome

首页 / 软件开发 / C++ / C++中随机存取文件的处理

C++中随机存取文件的处理2009-10-14 IT专家网 vivian和许多的C++程序一样,有些人更喜欢用原先的C语言方式处理问题,如果你恰好也是这些人中的一员,就应该学习一下这篇文章。

基本的文件操作有

◆fopen——打开文件,指定文件以怎样的方式打开(读/写)以及类型(二进制/文本)

◆fclose——关闭已经打开的文件

◆fread——读取文件

◆fwrite——写文件

◆fseek/fsetpos——将文件指示器转移到文件中的某一地方

◆ftell/fgetpos——可以告诉你文件指示器所在的位置

文件有两种基本类型:文本和二进制。在这两者之中,通常二进制类型是较容易解决的。由于在文本中处理随机存取并不常用,我们会在本文中重点关注二进制文件的处理。上面列出的操作中的前四项可用于文本文件和随机存取文件。后面的两项则仅用于随机存取。

随机存取意味着我们可以在文件的任意部分之间进行切换,且可以从中读写数据而不需要通读整篇文件。

二进制文件

二进制文件是任意长度的文件,它保存有从0到0xff(0到255)不等的字节值。这些字节在二进制文件中没有任何意义,与此不同的是,在文本文件中,值为13就意味着回车,10意味着换行,26意味着文件结束,而读取文本文件的软件要能够解决这些问题。

在现在的术语中,我们将二进制文件称为包含了字节的字符流,大多数语言倾向于将其理解为字符流而不是文件。重要的部分是数据流本身而不是其来源。在C语言中,你能从文件或数据流方面来考虑数据。或者,你可以将其理解为一组长的数组。通过随机存取,你可以读写数组的任意部分。

例一:
// ex1.c : Defines the entry point for the console application.
//
#include < stdio.h>
#include < string.h>
#include < windows.h>
int FileSuccess(FILE * handle,const char * reason, const char * path) {
OutputDebugString( reason );
OutputDebugString( path );
OutputDebugString(" Result : ");
if (handle==0)
{
OutputDebugString("Failed");
return 0;
}
else
{
OutputDebugString("Suceeded");
return 1;
}
}
int main(int argc, char * argv[])
{
const char * filename="test.txt";
const char * mytext="Once upon a time there were three bears.";
int byteswritten=0;
FILE * ft= fopen(filename, "wb");
if (FileSuccess(ft,"Opening File: ", filename)) {
fwrite(mytext,sizeof(char),strlen(mytext), ft);
fclose( ft );
}
printf("len of mytext = %i ",strlen(mytext));
return 0;
}

这段代码显示了一个简单的打开待写的二进制文件,文本字符(char*)会写入该文件。通常你会使用文本文件但是笔者想证明你可以向二进制文件写入文本。

// ex1.c

#include < stdio.h>
#include < string.h>
int main(int argc, char * argv[])
{
const char * filename="test.txt";
const char * mytext="Once upon a time there were three bears.";
int byteswritten=0;
FILE * ft= fopen(filename, "wb") ;
if (ft) {
fwrite(mytext,sizeof(char),strlen(mytext), ft) ;
fclose( ft ) ;
}
printf("len of mytext = %i ",strlen(mytext)) ;
return 0;
}