C方式:
写:
FILE *pFile = fopen("1.txt", "w");
fwrite("http://www.pcslonline.com", 1, strlen("http://www.pcslonline.com"), pFile);
fclose(pFile);
读:
FILE *pFileRead = fopen("1.txt", "r");
char *pBuf;
fseek(pFileRead, 0, SEEK_END); //把文件指针移动到文件结尾
int length = ftell(pFileRead);//取文件长度
pBuf = new char[length + 1];//多取一位,最后一位放0;
rewind(pFileRead);//重新把文件指针移动到开头
fread(pBuf, 1, length, pFileRead);
pBuf[length] = 0;
MessageBox(pBuf);//MessageBox函数遇到 0 就停止。
fclose(pFileRead);
定长读文件:
FILE *pFileRead = fopen("1.txt", "r");
1.//char ch[100] = {0};//全部初始化为0;
2.char ch[100];
memset(ch, 0, 100);//全部初始化为0;
fread(ch, 1, 100, pFileRead);
MessageBox(ch);//MessageBox函数遇到 0 就停止。
C++方式: #include <fstream.h>
写:
ofstream ofs(_T("2.txt"));
ofs.write(_T("minzhenfei"), strlen(_T("minzhenfei")));
ofs.close();
读:
ifstream ifs("2.txt");
char ch[100];
memset(ch, 0, 100);
ifs.read(ch, 100);
ifs.close();
MessageBox(ch);
SDK方式:
写:
HANDLE hFile = CreateFile("3.txt", GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
DWORD dwFileWrite;
//CHAR ch[] = "minzhenfei shi da tiancai";
LPSTR ch = "Hello world!";
WriteFile(hFile, ch, lstrlen(ch), &dwFileWrite, NULL);
CloseHandle(hFile);
读:
HANDLE hFileRead = CreateFile("3.txt", GENERIC_READ, 0, NULL, OPEN_EXISTING , FILE_ATTRIBUTE_NORMAL, NULL);
CHAR ch[100];
DWORD dwReads;
ReadFile(hFileRead, ch, 100, &dwReads, NULL);
CloseHandle(hFileRead);
ch[dwReads] = 0;
MessageBox(ch);
MFC方法:
写:
CFile fileWrite("4.txt", CFile::modeCreate | CFile::modeWrite );
fileWrite.Write("Hello MFC!", lstrlen("Hello MFC!"));
fileWrite.Close();
读:
CFile fileRead("4.txt", CFile::modeRead);
CHAR *pBuf;
DWORD strlen;
strlen = fileRead.GetLength();
pBuf = new CHAR[strlen + 1];
fileRead.Read(pBuf, strlen);
pBuf[strlen] = 0;
fileRead.Close();
MessageBox(pBuf);