很基础的一些东西,随便记一下……
代码:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;int main(int argc, char* argv[])
{
if ( (argc != 3) && (argc != 4) )
{
cout<<"使用方法:file /r 文件名"<<endl;
cout<<" file /w 文件名 写入内容"<<endl;
return 1;
}FILE* pFile;
pFile = fopen(argv[2],"a+");
if (pFile==NULL)
{
cout<<"打开文件失败"<<endl;
return 1;
}if (strcmp(argv[1],"/r") == 0)
{
char str[200];
memset(str,0,200*sizeof(char));
fread(str,sizeof(char),200,pFile);
cout<<"读取的数据是:"<<endl<<str<<endl;
fclose(pFile);
}if (strcmp(argv[1],"/w") == 0)
{
int iNumOfFile;
iNumOfFile=fwrite(argv[3],1,strlen(argv[3]),pFile);
if (iNumOfFile != strlen(argv[3]))
{
cout<<"写入文件失败!"<<endl;
return 1;
}
else
{
cout<<"写入文件成功!"<<endl;
}
}
return 0;
}
打开文件时的一些标志含义:
"r"
Opens for reading. If the file does not exist or cannot be found, the fopen call fails.
"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.
"r+"
Opens for both reading and writing. (The file must exist.)
"w+"
Opens an empty file for both reading and writing. If the given file exists, its contents are destroyed.
"a+"
Opens for reading and appending; the appending operation includes the removal of the EOF marker before new data is written to the file and the EOF marker is restored after writing is complete; creates the file first if it doesn’t exist.
已经有(0)位网友发表了评论,你也评一评吧!
原创文章如转载,请注明:转载自Eddy Blog
原文地址:http://www.rrgod.com/program/459.html 欢迎订阅Eddy Blog。