#include <iostream>
#include <string>
#include <string.h>
#include <cstdlib>
#include <fstream>
#include <streambuf>
#include <sstream>
using namespace std;
string C_Read_And_Write_File(const char* FileName,const char* Operator,const char *WriteFileContent)
{
FILE *fp = fopen(FileName,Operator);
if(fp == NULL)
{
printf("Open File %s is faild",FileName);
return string();
}
if(strcmp(Operator,"rb") == 0)
{
//将文件流指针移动到文件末尾
fseek(fp,0,SEEK_END);
//记录指针偏移量
size_t FileLength = ftell(fp);
//将指针回溯到文件头
rewind(fp);
//开辟空间
char* FileData = (char *)malloc(FileLength + 1);
//读入文件内容到FileData数组
fread(FileData,1,FileLength,fp);
FileData[FileLength] = '\0';
//关闭文件流
fclose(fp);
//返回string类型
string FileContent(FileData);
//释放内存空间
free(FileData);
return FileContent;
}
else if(strcmp(Operator,"wb") == 0)
{
//写文件
fwrite(WriteFileContent,strlen(WriteFileContent),1,fp);
fclose(fp);
return string();
}
else if(strcmp(Operator,"ab") == 0)
{
//追加文件
fwrite(WriteFileContent,strlen(WriteFileContent),1,fp);
fclose(fp);
return string();
}
else
{
cout << "输入参数有误" << endl;
return string();
}
}
string CPP_Read_And_Write_File(const char* FileName,string Operator,string content)
{
//读文件
if(Operator == "R")
{
ifstream in(FileName);
istreambuf_iterator<char> begin(in);
istreambuf_iterator<char> end;
string some_str(begin,end);
cout << some_str << endl;
return some_str;
}
//读文件
/*std::ifstream in(FileName);
std::ostringstream tmp;
tmp << in.rdbuf();
std::string str = tmp.str();
return str;*/
//写文件
else if(Operator == "W")
{
fstream ifs;
ifs.open(FileName,ios::out);
ifs << content;
ifs.close();
return string();
}
//追加文件
else if(Operator == "A")
{
fstream ifs;
ifs.open(FileName,ios::out | ios::app);
ifs << content;
ifs.close();
return string();
}
else
{
cout << "输入参数有误" << endl;
return string();
}
}
int main(int argc,char *argv[])
{
//const char* FileName 文件名
//const char* Operator 读、写、追加
//const char *WriteFileContent 要写的文件内容,读文件传空即可
C_Read_And_Write_File("./Demo.txt","rb",NULL);
CPP_Read_And_Write_File("./Demo.txt","A","qqqqq");
return 0;
}
Linux C/C++ 读写文件
最新推荐文章于 2024-05-15 13:34:30 发布