1.C语言对文件的操作
fseek(pFile,0,SEEK_END); //把文件指针移到文件末尾
int n=ftell(pFile); //得到文件长度
rewind(pFile); //把指针移回文件头 fseek(pFile,0,SEEK_BEGIN)
pbuf=new char[n+1];
pbuf[n]=0; //文件尾加\0 作为文件结束符
fread(pbuf,1,n,pFile);
//-------------正常读写操作----------------
void CTxtView::OnFileWrite()
{
// TODO: Add your command handler code here
FILE *fp;
fp=fopen("c:\\2.txt","w");
fwrite("我爱我家",1,strlen("我爱我家"),fp);
fclose(fp);
//fflush(fp);
}
void CTxtView::OnFileRead()
{
// TODO: Add your command handler code here
FILE *fp;
fp=fopen("c:\\2.txt","r");
char ch[100];
memset(ch,0,100);
fread(ch,1,100,fp);
fflush(fp);
MessageBox(ch);
}
//--------------正确写入数字-----------------
/*由于数字和二进制码的区别,所以写入数据要特别注意可以用itoa()函数进行转化*/
FILE *pFile=fopen("2.txt","w");
int i=98341; //非要使他可用,可增加 itoa(i,ch,10);
fwrite(&i,4,1,pFile);
void CTxtView::OnFileWrite()
{
// TODO: Add your command handler code here
char ch[10];
memset(ch,0,10);
FILE *fp;
int i=35678;
fp=fopen("c:\\3.txt","wb");
itoa(i,ch,10);
fwrite(&ch,1,10,fp);
MessageBox(ch);
fclose(fp);
//fflush(fp);
}
2.C++中对文件的操作
需要添加头文件fstream.h
void CTxtView::OnFileWrite()
{
// TODO: Add your command handler code here
ofstream os("C:\\4.txt");
os.write("I LOVE YOU",strlen("I LOVE YOU"));
os.close();
}
void CTxtView::OnFileRead()
{
// TODO: Add your command handler code here
char ch[100];
memset(ch,0,100);
ifstream ifs("c://4.txt",ios::in);
ifs.read(ch,100);
MessageBox(ch);
ifs.close();
}
//循环读取文件的每一行
ifs.clear();
while(!ifs.getline(ch,100).eof())
{
;
}
eof()函数,当到文件末尾时会返回false。
下一次重新 getline 之前,需要 ifs.clear()清除 eof标志
3.win32 API函数对文件的操作
void CTxtView::OnFileWrite()
{
// TODO: Add your command handler code here
CFile file("C:\\5.txt",CFile::modeCreate|CFile::modeWrite);
file.Write("我爱我家",strlen("我爱我家"));
file.Close();
}
void CTxtView::OnFileRead()
{
// TODO: Add your command handler code here
char ch[100];
memset(ch,0,100);
ifstream ifs("c://4.txt",ios::in);
ifs.read(ch,100);
MessageBox(ch);
ifs.close();
}