step1:新建一个单文档MFA App Wizard程序。
step2:在菜单项里添加“写入文件”和“读取文件”,在资源视图里,选着Menu然后双击就可添加,ID分别取为“IDM_FILE_WRITE”和"IDM_FILE_READ",
step3:在“写入文件”和“读取文件”上,右击鼠标,选着“Class Wizard”,然后就可以添加到CPropView类,然后,选着“Message”为“COMMAND”->AddFunction->Code
step4:就可以在生成的成员函数中,分别coding了 ,然后介绍各个关于文件操作的类和结构体以及函数。
FILE struct:Stores information about current state of stream; used in all stream I/O operations.
fopen函数:FILE *fopen( const char *filename, const char *mode); //open a file
第一个参数指向常量的指针类型,文件名,指出要打开的文件,第二也是指向常量的指针类型,打开的方式:
“r”:Opens for reading
"w":Opens an empty file for writing. If the given file exists, its contents are destroyed.
“a”:Opens for writing at the end of the file (appending) without removing the EOF marker before writing new data to the file; creates the file first if it doesn’t exist.
...具体看MSDN
fwrite函数:写入数据。写入数据后,然后有一个文件指针就会指在下一个文件写入的起始地址。那么怎么把调用后fwrite的指针移动到起始位置呢?用fseek();函数
size_t fwrite( const void *buffer, size_t size, size_t count, FILE *stream );
parameter1:第一个参数,是一个指向常量的指针,指向要写入的数据
parameter2:Item size in bytes 如果设置为1,就表示一个项的大小为1个字节,那么如果要传入6个字节,那么第三个参数要传入6.如果设置为2,第三个为3
如果我们传的是一个整型,那么就可以设置为4bit。
parameter3:Maximum number of items to be written
当缓存区没有满,那么是不回往磁盘写入文件,那么要 用fclose()函数,把文件关闭,就能够写入磁盘文件。但是下一次写入的时候,需要再次打开。
fflush:Flushes a stream刷新缓存区,这样就不需要关闭文件就能够让缓存区的文件输出。
fwrite("nihao",1,strlen("nihao"),pFile);
fseek(pFile,0,SEEK_SET); //将文件指针重新指到开头的位置
fwrite("123",1,strlen("123"),pFile);
fflush(pFile); //刷新缓存区域
这样就输出了123ao
知识补充,我们在往磁盘文件中写入数据的时候,要多写一个数据,多写的一个是空数据,那么在读的时候,就不会读出没有初始化的内存的部分。或者在recv的时候,记得
fwrite("nihao",1,strlen("nihao") + 1,pFile); //缺点,会增大文件的体积。
或者用。
memset(recvBuf,0,100); //这样在设置buff的时候,可以设置为0
我们在接收文件的时候,需要获得文件的长度,这样就可以按照文件的长度来定义recvBuf的长度了。
ftell():
Gets the current position of a file pointer.
先用fseek()将文件指针移动到文件的结尾处,然后用ftell获得current position of a file pointer,就可以得到文件的长度。
用完之后,记得将文件指针移动到文件的开头,记得用rewind函数。void rewind( FILE *stream);
void CFileView::OnFileRead()
{
// TODO: Add your command handler code here
FILE *pFile = fopen("1.txt","r");
// char readBuf[100];
//memset(readBuf,0,100);//初始化为0
//fread(readBuf,1,100,pFile);
//MessageBox(readBuf);
//fclose(pFile);
char *pBuf;
fseek(pFile,0,SEEK_END ); //将文件指针移动到了文件结尾
long len = ftell(pFile);
rewind(pFile); //将文件指标重新放到文件的开始处
pBuf = new char[len+1]; //多存放,用来存放\0
fread(pBuf,1,len,pFile);
pBuf[len] = 0;
MessageBox(pBuf);
fclose(pFile);
}