文件操作.docx

上传人:b****8 文档编号:28299227 上传时间:2023-07-10 格式:DOCX 页数:16 大小:292.69KB
下载 相关 举报
文件操作.docx_第1页
第1页 / 共16页
文件操作.docx_第2页
第2页 / 共16页
文件操作.docx_第3页
第3页 / 共16页
文件操作.docx_第4页
第4页 / 共16页
文件操作.docx_第5页
第5页 / 共16页
点击查看更多>>
下载资源
资源描述

文件操作.docx

《文件操作.docx》由会员分享,可在线阅读,更多相关《文件操作.docx(16页珍藏版)》请在冰豆网上搜索。

文件操作.docx

文件操作

文件操作

1.文件的读取与写入

新建一个MFC单文档应用程序(工程名取:

File),打开菜单资源新建一个文件菜单,并在其下添加以下菜单项(ID:

IDM_FILE_READ,Caption:

读取)和(ID:

IDM_FILE_WRITE,Caption:

写入),并分别给它们添加CFileView类上的命令响应,编辑:

void CFileView:

:

OnFileRead()  

    // TODO:

 Add your command handler code here 

    FILE *pFile=fopen("1.txt","r");//为了读取而打开一个文件 

//    char ch[100]; 

//    memset(ch,0,100); 

    //将字符数组中所有的数据都设为零,这样读取时,就只读取到有字符的位置 

//    fread(ch,1,100,pFile);//读取文件 

//    MessageBox(ch); 

    char *pBuf; 

    fseek(pFile,0,SEEK_END);//将文件的指针移到文件的末尾 

    int len=ftell(pFile);//获取文件的大小 

    pBuf=new char[len+1];//根据文件的大小分配内存,多分配一个是为了存取'\0' 

    rewind(pFile);//这个函数可以将文件指针移到文件的开始处 

    fread(pBuf,1,len,pFile);//读取len所表示的文件的长度的数据 

    pBuf[len]=0;//将数组的最后个元素设置为0,因为数据索引是从0开始的,所以len表示最后一个 

    MessageBox(pBuf); 

    fclose(pFile); 

    //fflush(pFile);//刷新缓冲区,让缓冲区的数据写入文件 

 

void CFileView:

:

OnFileWrite()  

    // TODO:

 Add your command handler code here 

    FILE *pFile=fopen("1.txt","w");//为了写入而打开一个文件 

    fwrite("",1,strlen(""),pFile); 

    //把字符串写入文件 

    //fwrite("",1,strlen("")+1,pFile); 

    //为了让读取到指定字符就结束,+1是在文件中多写入一个字节,多写的字节为空,默认也是0,就是字符串的结尾 

    //fwrite("",1,strlen(""),pFile); 

    //还可以再次写入,位置是上次写入后文件指针所在的位置 

 

    //fseek(pFile,0,SEEK_SET);//将文件的指针位置设为零 

 

    //fwrite("ftp:

//10.6.17.19",1,strlen("ftp:

//10.6.17.19"),pFile); 

    //fclose(pFile);//关闭文件,表明文件的写操作已完成,缓冲区内容将写入文件 

    fflush(pFile);//刷新缓冲区,让缓冲区的数据写入文件 

}

2.文件写入时经常会碰到的问题

void CFileView:

:

OnFileWrite()  

    //FILE *pFile=fopen("2.txt","w"); 

    FILE *pFile=fopen("2.txt","wb"); 

    char ch[3]; 

    ch[0]='a'; 

    ch[1]=10;//10实际上指换行符 

    ch[2]='b'; 

    fwrite(ch,1,3,pFile);//写入 

    fclose(pFile); 

    //运行可以发现在文件里写入了4个字节,回车符13占了两个字节 

    //转换成十六制可以发现:

61 0D 0A 62        ;a..b 

 } 

 

void CFileView:

:

OnFileRead()  

    //FILE *pFile=fopen("2.txt","r");//缺省是按文本方式(t)打开 

    FILE *pFile=fopen("2.txt","rb");//以二进制方式(b)打开 

    char ch[100]; 

    fread(ch,1,3,pFile);//读取文件 

    ch[3]=0; 

    MessageBox(ch); 

    fclose(pFile); 

    //以文本方式写入的文件 

    //以文本方式打开文件用3个字节读取发现仍然可以读出来 

    //以二进制方式用3个字符打开不能将b读出,只能读到61 0D 0A 

     //以二进制方式写入的文件 

    //以二进制方式用3个字符打开能将b读出 

}

二进制文件和文本文件

3.一个问题

98341,将这个整数保存到文件中,要求在以记事本程序打开文件时,显示的是98341。

void CFileView:

:

OnFileWrite()  

    FILE *pFile=fopen("3.txt","w"); 

    int i=98341; 

  char ch[5]; 

/*  ch[0]=9+48;//以ASCII码存进去 

    ch[1]=8+48; 

    ch[2]=3+48; 

    ch[3]=4+48; 

    ch[4]=1+48; 

*/

itoa(i,ch,10);

    //fwrite(&i,4,1,pFile); 

    fwrite(ch,1,5,pFile); 

    fclose(pFile); 

 }

===============================================

fopen,_wfopen

Openafile.

FILE*fopen(constchar*filename,constchar*mode);

FILE*_wfopen(constwchar_t*filename,constwchar_t*mode);

Function

RequiredHeader

Compatibility

fopen

ANSI,Win95,WinNT

_wfopen

or

WinNT

Foradditionalcompatibilityinformation,seeCompatibilityintheIntroduction.

Libraries

LIBC.LIB

Singlethreadstaticlibrary,retailversion

LIBCMT.LIB

Multithreadstaticlibrary,retailversion

MSVCRT.LIB

ImportlibraryforMSVCRT.DLL,retailversion

Thec,n,andtmodeoptionsareMicrosoftextensionsforfopenand_fdopenandshouldnotbeusedwhereANSIportabilityisdesired.

ReturnValue

Eachofthesefunctionsreturnsapointertotheopenfile.Anullpointervalueindicatesanerror.

Parameters

filename

Filename

mode

Typeofaccesspermitted

Remarks

Thefopenfunctionopensthefilespecifiedbyfilename._wfopenisawide-characterversionoffopen;theargumentsto_wfopenarewide-characterstrings._wfopenandfopenbehaveidenticallyotherwise.

Generic-TextRoutineMappings

TCHAR.HRoutine

_UNICODE&_MBCSNotDefined

_MBCSDefined

_UNICODEDefined

_tfopen

fopen

fopen

_wfopen

Thecharacterstringmodespecifiesthetypeofaccessrequestedforthefile,asfollows:

"r"

Opensforreading.Ifthefiledoesnotexistorcannotbefound,thefopencallfails.

"w"

Opensanemptyfileforwriting.Ifthegivenfileexists,itscontentsaredestroyed.

"a"

Opensforwritingattheendofthefile(appending)withoutremovingtheEOFmarkerbeforewritingnewdatatothefile;createsthefilefirstifitdoesn’texist.

"r+"

Opensforbothreadingandwriting.(Thefilemustexist.)

"w+"

Opensanemptyfileforbothreadingandwriting.Ifthegivenfileexists,itscontentsaredestroyed.

"a+"

Opensforreadingandappending;theappendingoperationincludestheremovaloftheEOFmarkerbeforenewdataiswrittentothefileandtheEOFmarkerisrestoredafterwritingiscomplete;createsthefilefirstifitdoesn’texist.

Whenafileisopenedwiththe"a"or"a+"accesstype,allwriteoperationsoccurattheendofthefile.Thefilepointercanberepositionedusingfseekorrewind,butisalwaysmovedbacktotheendofthefilebeforeanywriteoperationiscarriedout.Thus,existingdatacannotbeoverwritten.

The"a"modedoesnotremovetheEOFmarkerbeforeappendingtothefile.Afterappendinghasoccurred,theMS-DOSTYPEcommandonlyshowsdatauptotheoriginalEOFmarkerandnotanydataappendedtothefile.The"a+"modedoesremovetheEOFmarkerbeforeappendingtothefile.Afterappending,theMS-DOSTYPEcommandshowsalldatainthefile.The"a+"modeisrequiredforappendingtoastreamfilethatisterminatedwiththeCTRL+ZEOFmarker.

Whenthe"r+","w+",or"a+"accesstypeisspecified,bothreadingandwritingareallowed(thefileissaidtobeopenfor“update”).However,whenyouswitchbetweenreadingandwriting,theremustbeaninterveningfflush,fsetpos,fseek,orrewindoperation.Thecurrentpositioncanbespecifiedforthefsetposorfseekoperation,ifdesired.

Inadditiontotheabovevalues,thefollowingcharacterscanbeincludedinmodetospecifythetranslationmodefornewlinecharacters:

t

Openintext(translated)mode.Inthismode,CTRL+Zisinterpretedasanend-of-filecharacteroninput.Infilesopenedforreading/writingwith"a+",fopenchecksforaCTRL+Zattheendofthefileandremovesit,ifpossible.ThisisdonebecauseusingfseekandftelltomovewithinafilethatendswithaCTRL+Z,maycausefseektobehaveimproperlyneartheendofthefile.

Also,intextmode,carriagereturn–linefeedcombinationsaretranslatedintosinglelinefeedsoninput,andlinefeedcharactersaretranslatedtocarriagereturn–linefeedcombinationsonoutput.WhenaUnicodestream-I/Ofunctionoperatesintextmode(thedefault),thesourceordestinationstreamisassumedtobeasequenceofmultibytecharacters.Therefore,theUnicodestream-inputfunctionsconvertmultibytecharacterstowidecharacters(asifbyacalltothembtowcfunction).Forthesamereason,theUnicodestream-outputfunctionsconvertwidecharacterstomultibytecharacters(asifbyacalltothewctombfunction).

b

Openinbinary(untranslated)mode;translationsinvolvingcarriage-returnandlinefeedcharactersaresuppressed.

Iftorbisnotgiveninmode,thedefaulttranslationmodeisdefinedbytheglobalvariable_fmode.Iftorbisprefixedtotheargument,thefunctionfailsandreturnsNULL.

FormoreinformationaboutusingtextandbinarymodesinUnicodeandmultibytestream-I/O,seeTextandBinaryModeFileI/OandUnicodeStreamI/OinTextandBinaryModes.

c

Enablethecommitflagfortheassociatedfilenamesothatthecontentsofthefilebufferarewrittendirectlytodiskifeitherfflushor_flushalliscalled.

n

Resetthecommitflagfortheassociatedfilenameto“no-commit.”Thisisthedefault.ItalsooverridestheglobalcommitflagifyoulinkyourprogramwithCOMMODE.OBJ.Theglobalcommitflagdefaultis“no-commit”unlessyouexplicitlylinkyourprogramwithCOMMODE.OBJ.

Validcharactersforthemodestringusedinfopenand_fdopencorrespondtooflagargumentsusedin_openand_sopen,asfollows.

CharactersinmodeString

EquivalentoflagValuefor_open/_sopen

a

_O_WRONLY|_O_APPEND(usually_O_WRONLY|_O_CREAT|_O_APPEND)

a+

_O_RDWR|_O_APPEND(usually_O_RDWR|_O_APPEND|_O_CREAT)

r

_O_RDONLY

r+

_O_RDWR

w

_O_WRONLY(usually_O_WRONLY|_O_CREAT|_O_TRUNC)

w+

_O_RDWR(usually_O_RDWR|_O_CREAT|_O_TRUNC)

b

_O_BINARY

t

_O_TEXT

c

None

n

None

Example

/*FOPEN.C:

Thisprogramopensfilesnamed"data"

*and"data2".It usesfclosetoclose"data"and

*_fclosealltocloseallremainingfiles.

*/

#include

FILE*stream,*stream2;

voidmain(void)

{

 intnumclosed;

 /*Openforread(willfailiffile"data"doesnotexist)*/

 if((stream =fopen("data","r"))==NULL)

    printf("Thefile'data'wasnotopened\n");

 else

    printf("Thefile'data'wasopened\n");

 /*Openforwrite*/

 if((stream2=fopen("data2","w+"))==NULL)

    printf("Thefile'data2'wasnotopened\n");

 else

    printf("Thefile'data2'wasopened\n");

 /*Closestream*/

 if(fclose(stream))

    printf("Thefile'data'wasnotclosed\n");

 /*Allotherfilesareclosed:

*/

 numclosed=_fcloseall();

 printf("Numberoffilesclosedby_fcloseall:

%u\n",numclosed);

}

Output

Thefile'data'wasopened

Thefile'data2'wasopened

Numberoffilesclosedby_fcloseall:

1

===============================================

4.C++中对文件操作

void CFileView:

:

OnFileWrite()  

    ofstream ofs("4.txt");//构造一个对象传递文件名4.txt 

    //C++中写入文件可以用这个类 

    ofs.write("",strlen("")); 

    ofs.close(); 

 } 

 

void CFileView:

:

OnFileRead()  

    ifstream ifs("4.txt");//读入一个文件用这个类 

    char ch[100]; 

    memset(ch,0,100);//将字符数组中的内存都设为零 

    ifs.read(ch,100); 

展开阅读全文
相关资源
猜你喜欢
相关搜索

当前位置:首页 > PPT模板 > 其它模板

copyright@ 2008-2022 冰豆网网站版权所有

经营许可证编号:鄂ICP备2022015515号-1