文件操作

(1)C函數:
        fopen,fwrite,fread,fflush,fclose,fseek,ftell。(可參考:http://blog.csdn.net/andylin02/archive/2007/03/12/1526554.aspx)

----------------例子------------------------------------------------
        FILE *pFile=fopen("1.txt","w");

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

        char chArr[100];
        memset(chArr,0,100);
        fread(chArr,1,100,pFile);
        fclose();
----------------------------------------------------------------------

(2)C++:(應用較少)
        ofstream(...), write, read, close。(fstream.h)

----------------例子------------------------------------------------
        ofstream ofs("1.txt");
        ofs.write("content");
        ofs.close();

        ifstream ifs("1.txt");
        char chArr[100];
        memset(chArr,0,100);
        ifs.read(chArr,100);
        ifs.close();
----------------------------------------------------------------------

(3)Win32 API:
        CreateFile,WriteFile,ReadFile,CloseHandle。

----------------例子------------------------------------------------
        HANDLE hFile;
        hFile=CreateFile("1.txt",GENERIC_WRITE,0,NULL,CREATE_NEW,FILE_ATTRIBUTE_NORMAL,NULL);
        DWORD dwWrites; //接收實際寫入的字節數。
        WriteFile(hFile, "content" ,strlen("content"), dwWrites, NULL);
        CloseHandle(hFile);

        hFile=CreateFile("1.txt", GENERIC_READ, 0, NULL, OPEN_EXSITING, FILE_ATTRIBUTE_NORMAL, NULL);
        char chArr[100];
        DWORD dwReads;
        memset(chArr, 0, 100);
        ReadFile(hFile, chArr, 100, &dwReads, NULL);
        CloseHandle(hFile);
----------------------------------------------------------------------

(4)MFC:(常用)
        CFile,Write,Read,Close,SeekToBegin,SeekToEnd,GetLength,。

----------------例子------------------------------------------------
        CFile file("1.txt", CFile::modeCreate | CFile::modeWrite);
        file.Write("content", strlen("content"));
        file.Close();

        CFile fileR("1.txt", CFile::modeRead);
        DWORD dwFileLen=fileR.GetLength();
        char *pBuf=new char[dwFileLen+1];
        pBuf[dwFileLen]=0;
        fileR.Read(pBuf, dwFileLen);
        fileR.Close();
---------------------------------------------------------------------

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章